Example
main.rs
extern crate serde;
extern crate serde_json;
// Import this crate to derive the Serialize and Deserialize traits.
#[macro_use] extern crate serde_derive;
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 1, y: 2 };
// Convert the Point to a packed JSON string. To convert it to
// pretty JSON with indentation, use `to_string_pretty` instead.
let serialized = serde_json::to_string(&point).unwrap();
// Prints serialized = {"x":1,"y":2}
println!("serialized = {}", serialized);
// Convert the JSON string back to a Point.
let deserialized: Point = serde_json::from_str(&serialized).unwrap();
// Prints deserialized = Point { x: 1, y: 2 }
println!("deserialized = {:?}", deserialized);
}
Cargo.toml
[package]
name = "serde-example"
version = "0.1.0"
build = "build.rs"
[dependencies]
serde = "0.9"
serde_json = "0.9"
serde_derive = "0.9"