Serde - tutorial
Page content
Serde (serializing and deserializing) is one of the most frequently used library in Rust.
The library is production ready, usually used with Serde JSON (because of the popularity of REST APIs).
Serialization
In other words, serialization is used to save the state of an object in order to be able to recreate it when needed.
When to use serialization
Through serialization, a developer can perform actions such as:
- Sending the object to a remote application by using a web service
- Passing an object from one domain to another
- Passing an object through a firewall as a JSON or XML string
- Maintaining security or user-specific information across applications
Supported data formats
https://serde.rs/#data-formats
JSON, YAML, TOML, URL, D-Bus,
The official simplest example
Cargo.toml
:
[dependencies]
serde = { version = "^1.0", features = ["derive"] }
serde_json = "^1.0"
This example serialize/deserialize the custom struct Point
:
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 1, y: 2 };
// Convert the Point to a JSON string.
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);
}