Serialization

RecipeCratesCategories
Serialize JSONserde_jsoncat-encoding
monostatemonostatecat-encoding
serde-ignoredserde-ignoredcat-encoding

serde serde-crates.io serde-github serde-lib.rs

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

serde_json serde_json-crates.io serde_json-github serde_json-lib.rs

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

monostate monostate-crates.io monostate-github monostate-lib.rs

This library implements a type macro for a zero-sized type that is Serde deserializable only from one specific value.

serde-ignored

serde-ignored serde-ignored-crates.io serde-ignored-github serde-ignored-lib.rs