JSON in Rust with serde_json
Rust uses the serde ecosystem for serialization. Add these to your Cargo.toml:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Typed Deserialization
Derive #[derive(Deserialize)] on your struct, then call serde_json::from_str(&text)?.
Dynamic JSON with Value
Use serde_json::Value for parsing arbitrary/unknown JSON structures without defining a struct.
use serde::{Deserialize, Serialize};
use serde_json;
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: u32,
name: String,
is_active: bool,
}
fn main() -> Result<(), serde_json::Error> {
// Parse typed JSON
let json = r#"{"id":1,"name":"Alice","is_active":true}"#;
let user: User = serde_json::from_str(json)?;
println!("{}", user.name); // Alice
// Serialize to JSON string
let serialized = serde_json::to_string(&user)?;
// Pretty print
let pretty = serde_json::to_string_pretty(&user)?;
println!("{}", pretty);
// Dynamic Value
let value: serde_json::Value = serde_json::from_str(json)?;
println!("{}", value["name"]); // "Alice"
Ok(())
}