- serde
- serde_json
JSON serialize struct
examples/json/json-serialize-struct/Cargo.toml
[package] name = "json-serialize-struct" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0"
examples/json/json-serialize-struct/src/main.rs
use serde::Serialize; #[derive(Debug, Serialize)] #[allow(dead_code)] struct Thing { name: String, number: i8, numbers: Vec<i32>, } fn main() { let thing = Thing { name: String::from("Foo Bar"), number: 42, numbers: vec![23, 19], }; println!("{:#?}", &thing); let serialized = serde_json::to_string(&thing).unwrap(); println!("{serialized}"); }
Thing { name: "Foo Bar", number: 42, numbers: [ 23, 19, ], } {"name":"Foo Bar","number":42,"numbers":[23,19]}