Parse JSON into strongly typed Rust data structures
masterFor most use cases, you should map JSON data directly into strongly typed Rust structs or enums. This provides compile-time safety, IDE autocompletion, and informative error messages if the JSON structure does not match your type.
Requirements
Your data structures must implement the serde::Deserialize trait. You can use #[derive(Deserialize)] to implement this automatically.
use serde::{Deserialize, Serialize};
use serde_json::Result;
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
phones: Vec<String>,
}
fn typed_example() -> Result<()> {
let data = r""
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567"
]
}"";
// Parse the string of data into a Person object.
let p: Person = serde_json::from_str(data)?;
// Do things just like with any other Rust data structure.
println!("Please call {} at the number {}", p.name, p.phones[0]);
Ok(())
}