### Rust: Serialize and Deserialize Structs with miniserde Source: https://github.com/dtolnay/miniserde/blob/master/README.md This example demonstrates how to use the `miniserde` crate in Rust to derive `Serialize` and `Deserialize` traits for a custom struct. It shows how to convert the struct to a JSON string and then parse a JSON string back into the struct. This requires the `miniserde` dependency and Rust 1.68+. ```rust use miniserde::{json, Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Example { code: u32, message: String, } fn main() -> miniserde::Result<()> { let example = Example { code: 200, message: "reminiscent of Serde".to_owned(), }; let j = json::to_string(&example); println!("{}", j); let out: Example = json::from_str(&j)?; println!("{:?}", out); Ok(()) } ``` -------------------------------- ### Implement Custom Deserialize Trait for Percentage in Rust Source: https://context7.com/dtolnay/miniserde/llms.txt This Rust code demonstrates how to manually implement the `Deserialize` trait for a custom struct `Percentage`. It uses the `miniserde::make_place!` macro and defines a `Visitor` to handle float and nonnegative JSON values, enforcing specific validation rules for the Percentage type. The implementation includes unit tests to show successful and failed deserialization scenarios. ```rust use miniserde::{make_place, Result}; use miniserde::de::{Deserialize, Visitor}; use miniserde::json; make_place!(Place); struct Percentage(f64); impl Visitor for Place { fn float(&mut self, n: f64) -> Result<()> { if n >= 0.0 && n <= 100.0 { self.out = Some(Percentage(n)); Ok(()) } else { Err(miniserde::Error) } } fn nonnegative(&mut self, n: u64) -> Result<()> { if n <= 100 { self.out = Some(Percentage(n as f64)); Ok(()) } else { Err(miniserde::Error) } } } impl Deserialize for Percentage { fn begin(out: &mut Option) -> &mut dyn Visitor { Place::new(out) } } fn main() -> Result<()> { let valid: Percentage = json::from_str("75.5")?; println!("Percentage: {}", valid.0); // Output: Percentage: 75.5 // This would fail validation let invalid = json::from_str::("150.0"); assert!(invalid.is_err()); Ok(()) } ``` -------------------------------- ### Implement Custom Serialize Trait in Rust Source: https://context7.com/dtolnay/miniserde/llms.txt Explains how to manually implement the `Serialize` trait for custom types in Rust. This allows defining specific serialization logic by returning a `Fragment`. It's useful for types requiring non-standard serialization behavior. ```rust use miniserde::ser::{Fragment, Serialize}; use miniserde::json; use std::borrow::Cow; struct Timestamp(u64); impl Serialize for Timestamp { fn begin(&self) -> Fragment { Fragment::U64(self.0) } } struct Point { x: f64, y: f64, } impl Serialize for Point { fn begin(&self) -> Fragment { use miniserde::ser::Map; use std::borrow::Cow; struct PointMap<'a> { point: &'a Point, state: usize, } impl<'a> Map for PointMap<'a> { fn next(&mut self) -> Option<(Cow, &dyn Serialize)> { let state = self.state; self.state += 1; match state { 0 => Some((Cow::Borrowed("x"), &self.point.x)), 1 => Some((Cow::Borrowed("y"), &self.point.y)), _ => None, } } } Fragment::Map(Box::new(PointMap { point: self, state: 0 })) } } fn main() { let ts = Timestamp(1609459200); println!("{}", json::to_string(&ts)); // Output: 1609459200 let point = Point { x: 3.5, y: -2.0 }; println!("{}", json::to_string(&point)); // Output: {"x":3.5,"y":-2.0} } ``` -------------------------------- ### Serialize and Deserialize Enum Variants in Rust Source: https://context7.com/dtolnay/miniserde/llms.txt Demonstrates how to serialize and deserialize C-style enums (unit variants only) to and from JSON strings using miniserde. Enum variants can be renamed for flexibility. This requires the `Serialize` and `Deserialize` traits from the miniserde crate. ```rust use miniserde::{json, Serialize, Deserialize, Result}; #[derive(Serialize, Deserialize, Debug, PartialEq)] enum Status { Pending, #[serde(rename = "in_progress")] InProgress, Completed, Failed, } #[derive(Serialize, Deserialize, Debug)] struct Task { id: u32, status: Status, } fn main() -> Result<()> { let task = Task { id: 1, status: Status::InProgress, }; let json = json::to_string(&task); println!("{}", json); // Output: {"id":1,"status":"in_progress"} let parsed: Task = json::from_str(&json)?; assert_eq!(parsed.status, Status::InProgress); Ok(()) } ``` -------------------------------- ### Handle Nested Structures and Collections in Rust Source: https://context7.com/dtolnay/miniserde/llms.txt Illustrates miniserde's capability to handle arbitrarily nested structs, vectors, arrays, and options. The implementation is non-recursive, preventing stack overflows. This functionality relies on the `Serialize` and `Deserialize` traits. ```rust use miniserde::{json, Serialize, Deserialize, Result}; #[derive(Serialize, Deserialize, Debug)] struct Company { name: String, departments: Vec, } #[derive(Serialize, Deserialize, Debug)] struct Department { name: String, employees: Vec, budget: Option, } #[derive(Serialize, Deserialize, Debug)] struct Employee { id: u32, name: String, roles: Vec, } fn main() -> Result<()> { let company = Company { name: "TechCorp".to_owned(), departments: vec![ Department { name: "Engineering".to_owned(), budget: Some(500000.0), employees: vec![ Employee { id: 101, name: "Alice".to_owned(), roles: vec!["Backend".to_owned(), "DevOps".to_owned()], }, Employee { id: 102, name: "Bob".to_owned(), roles: vec!["Frontend".to_owned()], }, ], }, Department { name: "HR".to_owned(), budget: None, employees: vec![], }, ], }; let json = json::to_string(&company); println!("{}", json); let deserialized: Company = json::from_str(&json)?; println!("Deserialized company: {}", deserialized.name); println!("Departments: {}", deserialized.departments.len()); Ok(()) } ``` -------------------------------- ### Serialize data structure to JSON string Source: https://context7.com/dtolnay/miniserde/llms.txt Converts any type implementing the `Serialize` trait into a JSON string representation. The serialization process is infallible and returns a `String` directly. ```APIDOC ## Serialize JSON ### Description Converts any type implementing the `Serialize` trait into a JSON string representation. The serialization process is infallible and returns a `String` directly. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (*T where T: Serialize*) - Required - The data structure to serialize. ### Request Example ```rust use miniserde::{json, Serialize}; #[derive(Serialize)] struct User { id: u32, username: String, active: bool, score: f64, } let user = User { id: 42, username: "alice".to_owned(), active: true, score: 95.5, }; let json_string = json::to_string(&user); ``` ### Response #### Success Response (String) - **json_string** (String) - The resulting JSON string. #### Response Example ```json { "example": "{\"id\":42,\"username\":\"alice\",\"active\":true,\"score\":95.5}" } ``` ``` -------------------------------- ### Serialize Rust data structure to JSON string with miniserde Source: https://context7.com/dtolnay/miniserde/llms.txt Converts a Rust type implementing the `Serialize` trait into its JSON string representation using `miniserde::json::to_string`. This process is infallible and returns a `String`. It requires the `Serialize` derive macro on the data structure. ```rust use miniserde::{json, Serialize}; #[derive(Serialize)] struct User { id: u32, username: String, active: bool, score: f64, } fn main() { let user = User { id: 42, username: "alice".to_owned(), active: true, score: 95.5, }; let json_string = json::to_string(&user); println!("{}", json_string); // Output: {"id":42,"username":"alice","active":true,"score":95.5} } ``` -------------------------------- ### Rename struct fields with serde attribute Source: https://context7.com/dtolnay/miniserde/llms.txt Use the `#[serde(rename = "...")]` attribute to map Rust field names to different JSON keys. This is the only customization attribute supported. ```APIDOC ## Field Renaming ### Description Use the `#[serde(rename = "...")]` attribute to map Rust field names to different JSON keys. This is the only customization attribute supported. ### Method N/A (Attribute Usage) ### Endpoint N/A (Attribute Usage) ### Parameters None (Applies to struct fields) ### Request Example ```rust use miniserde::{json, Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct ApiResponse { #[serde(rename = "statusCode")] status_code: u32, #[serde(rename = "responseData")] response_data: String, error_message: Option, } // Serialization let response = ApiResponse { status_code: 200, response_data: "Success".to_owned(), error_message: None, }; let json = json::to_string(&response); println!("{}", json); // Deserialization let input = r#"{"statusCode":404,"responseData":"Not Found","error_message":"Resource missing"}"#; let parsed: ApiResponse = json::from_str(input).unwrap(); println!("{:?}", parsed); ``` ### Response #### Success Response (String/Struct) - Serialized output will use the renamed keys. - Deserialized input will map renamed keys to the specified Rust fields. #### Response Example ```json { "example": "{\"statusCode\":200,\"responseData\":\"Success\",\"error_message\":null}" } ``` ``` -------------------------------- ### Deserialize JSON string to Rust data structure with miniserde Source: https://context7.com/dtolnay/miniserde/llms.txt Parses a JSON string into a Rust type implementing the `Deserialize` trait using `miniserde::json::from_str`. It returns a `Result`, where errors are unit types. Requires the `Deserialize` derive macro on the target data structure. Handles optional fields gracefully. ```rust use miniserde::{json, Deserialize, Result}; #[derive(Deserialize, Debug)] struct Config { host: String, port: u32, timeout_ms: Option, } fn main() -> Result<()> { let json_input = r#"{ "host": "localhost", "port": 8080, "timeout_ms": 5000 }"#; let config: Config = json::from_str(json_input)?; println!("{:?}", config); // Output: Config { host: "localhost", port: 8080, timeout_ms: Some(5000) } // Handle missing optional fields let minimal = r#"{"host": "0.0.0.0", "port": 3000}"#; let config2: Config = json::from_str(minimal)?; println!("{:?}", config2); // Output: Config { host: "0.0.0.0", port: 3000, timeout_ms: None } Ok(()) } ``` -------------------------------- ### Work with untyped JSON values using miniserde::json::Value Source: https://context7.com/dtolnay/miniserde/llms.txt Dynamically construct and manipulate JSON data using the `miniserde::json::Value` enum. Supports primitives, arrays, and objects with non-recursive drop for deep nesting. Can be serialized to a JSON string and deserialized from a JSON string. ```rust use miniserde::json::{Value, Array, Object, Number}; use miniserde::{json, Serialize, Deserialize}; fn main() { // Construct JSON values dynamically let mut obj = Object::new(); obj.insert("name".to_owned(), Value::String("Bob".to_owned())); obj.insert("age".to_owned(), Value::Number(Number::U64(30))); let mut arr = Array::new(); arr.push(Value::String("tag1".to_owned())); arr.push(Value::String("tag2".to_owned())); obj.insert("tags".to_owned(), Value::Array(arr)); let json_value = Value::Object(obj); // Serialize Value to JSON string let json_str = json::to_string(&json_value); println!("{}", json_str); // Output: {"name":"Bob","age":30,"tags":["tag1","tag2"]} // Deserialize JSON to Value let parsed: Value = json::from_str(&json_str).unwrap(); println!("{:?}", parsed); } ``` -------------------------------- ### Deserialize JSON string to data structure Source: https://context7.com/dtolnay/miniserde/llms.txt Parses a JSON string into any type implementing the `Deserialize` trait. Returns `Result` where errors contain no diagnostic information. ```APIDOC ## Deserialize JSON ### Description Parses a JSON string into any type implementing the `Deserialize` trait. Returns `Result` where errors contain no diagnostic information. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **json_input** (`&str`) - Required - The JSON string to deserialize. ### Request Example ```rust use miniserde::{json, Deserialize, Result}; #[derive(Deserialize, Debug)] struct Config { host: String, port: u32, timeout_ms: Option, } let json_input = r#"{ "host": "localhost", "port": 8080, "timeout_ms": 5000 }"#; let config: Config = json::from_str(json_input)?; ``` ### Response #### Success Response (200) - **T** (*T where T: Deserialize*) - The deserialized data structure. #### Response Example ```json { "example": "Config { host: \"localhost\", port: 8080, timeout_ms: Some(5000) }" } ``` #### Error Response - **miniserde::Error** - An error occurred during deserialization (no diagnostic info). ``` -------------------------------- ### Rename struct fields in JSON with #[serde(rename = "...")] in miniserde Source: https://context7.com/dtolnay/miniserde/llms.txt Maps Rust struct field names to different JSON keys during serialization and deserialization using the `#[serde(rename = "...")]` attribute. This is the primary customization attribute supported by Miniserde. ```rust use miniserde::{json, Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct ApiResponse { #[serde(rename = "statusCode")] status_code: u32, #[serde(rename = "responseData")] response_data: String, error_message: Option, } fn main() { let response = ApiResponse { status_code: 200, response_data: "Success".to_owned(), error_message: None, }; let json = json::to_string(&response); println!("{}", json); // Output: {"statusCode":200,"responseData":"Success","error_message":null} let input = r#"{"statusCode":404,"responseData":"Not Found","error_message":"Resource missing"}"#; let parsed: ApiResponse = json::from_str(input).unwrap(); println!("{:?}", parsed); // Output: ApiResponse { status_code: 404, response_data: "Not Found", error_message: Some("Resource missing") } } ``` -------------------------------- ### Work with untyped JSON values Source: https://context7.com/dtolnay/miniserde/llms.txt The `Value` enum represents any valid JSON value and supports non-recursive drop for arbitrarily deep nesting. Can be used for dynamic JSON manipulation. ```APIDOC ## Untyped JSON Values ### Description The `Value` enum represents any valid JSON value and supports non-recursive drop for arbitrarily deep nesting. Can be used for dynamic JSON manipulation. ### Methods - `json::to_string(&Value)`: Serializes a `Value` to a JSON string. - `json::from_str(&str)`: Deserializes a JSON string into a `Value`. ### Value Enum Variants - `Value::Null` - `Value::Bool(bool)` - `Value::Number(Number)` (Number can be `I64`, `U64`, `F64`) - `Value::String(String)` - `Value::Array(Array)` (Array is `Vec`) - `Value::Object(Object)` (Object is `std::collections::BTreeMap`) ### Example Usage ```rust use miniserde::json::{Value, Array, Object, Number}; use miniserde::{json, Serialize, Deserialize}; // Construct JSON values dynamically let mut obj = Object::new(); obj.insert("name".to_owned(), Value::String("Bob".to_owned())); obj.insert("age".to_owned(), Value::Number(Number::U64(30))); let mut arr = Array::new(); arr.push(Value::String("tag1".to_owned())); arr.push(Value::String("tag2".to_owned())); obj.insert("tags".to_owned(), Value::Array(arr)); let json_value = Value::Object(obj); // Serialize Value to JSON string let json_str = json::to_string(&json_value); println!("{}", json_str); // Deserialize JSON to Value let parsed: Value = json::from_str(&json_str).unwrap(); println!("{:?}", parsed); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.