intermediateSerialization
JSON with Serde
Serialize and deserialize JSON with serde_json.
JSON with Serde
Serialize and deserialize JSON with serde_json.
Difficulty
Intermediate
Code
rust
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Config {
name: String,
version: String,
debug: bool,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = Config {
name: "myapp".into(),
version: "1.0.0".into(),
debug: true,
};
let json = serde_json::to_string_pretty(&config)?;
println!("{}", json);
let parsed: Config = serde_json::from_str(&json)?;
println!("{:?}", parsed);
Ok(())
}Explanation
This example demonstrates how to use json with serde in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the serialization category to build a complete understanding of this topic.