Serialization
Recipe | Crates | Categories |
---|---|---|
Serialize JSON | ||
monostate | ||
serde-ignored |
[serde.incl: title (P1)](https://github.com/john-cd/rust_howto/issues/351)
De facto standard serialization library. Use in conjunction with sub-crates like serde_json for the specific format that you are using.
use serde::Deserialize; use serde::Serialize; // Define a struct and derive the Serialize and Deserialize traits #[derive(Serialize, Deserialize, Debug)] struct Person { // Rename the fields during serialization and deserialization #[serde(rename = "first_name")] first: String, #[serde(rename = "last_name")] last: String, // Skip serializing the age field if it is None. #[serde(skip_serializing_if = "Option::is_none")] age: Option<u8>, } fn main() { // Create an instance of the struct let person = Person { first: String::from("John"), last: String::from("Doe"), age: Some(30), }; // Serialize the struct to a JSON string let json = serde_json::to_string(&person).unwrap(); println!("Serialized: {}", json); // Deserialize the JSON string back to a struct let deserialized_person: Person = serde_json::from_str(&json).unwrap(); println!("Deserialized: {:?}", deserialized_person); }
Serialize JSON
use serde::Deserialize; use serde::Serialize; #[derive(Serialize, Deserialize, Debug)] struct Person { name: String, age: u8, email: String, } fn main() { // Create an instance of `Person` let person = Person { name: "Alice".to_string(), age: 30, email: "alice@example.com".to_string(), }; // Serialize the `Person` instance to a JSON string let json_string = serde_json::to_string(&person).unwrap(); println!("Serialized JSON: {}", json_string); // Deserialize the JSON string back into a `Person` instance let deserialized_person: Person = serde_json::from_str(&json_string).unwrap(); println!("Deserialized person: {:?}", deserialized_person); }
See also
monostate
This library implements a type macro for a zero-sized type that is Serde deserializable only from one specific value.
serde-ignored
[serde: write (P1)](https://github.com/john-cd/rust_howto/issues/352)
dedupe JSON with complex.md Supported formats