Rust:
Working with JSON

How to:

To work with JSON in Rust, the serde crate along with serde_json for serialization and deserialization is extensively used. First, ensure to include these in your Cargo.toml:

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

Example 1: Deserialize JSON to a Rust Struct

Define a Rust struct and use derive macros for Deserialize and Serialize:

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct User {
    id: u32,
    name: String,
    email: String,
}

fn main() {
    let json_data = r#"
        {
            "id": 1,
            "name": "Jane Doe",
            "email": "[email protected]"
        }
    "#;

    let user: User = serde_json::from_str(json_data).unwrap();

    println!("User ID: {}", user.id);
    println!("User Name: {}", user.name);
    println!("User Email: {}", user.email);
}

Output:

User ID: 1
User Name: Jane Doe
User Email: [email protected]

Example 2: Serialize a Rust Struct to JSON

Using the same User struct:

let user = User {
    id: 1,
    name: "Jane Doe".to_string(),
    email: "[email protected]".to_string(),
};

let json_data = serde_json::to_string(&user).unwrap();

println!("{}", json_data);

Output:

{"id":1,"name":"Jane Doe","email":"[email protected]"}

These examples demonstrate the basic flow of deserializing JSON into Rust structures and serializing Rust structures back into JSON strings. Serde provides a rich set of tools for working with JSON, including dealing with optional fields, complex nesting, and types not directly supported by JSON.