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

From Wikipedia, In computing, serialization is the process of translating a data structure or object state into a format that can be stored (for example, in a file or memory data buffer) or transmitted (for example, over a computer network) and reconstructed later (possibly in a different computer environment)

Serializing the data structure in an architecture-independent format means preventing the problems of byte ordering, memory layout, or simply different ways of representing data structures in different programming languages.

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

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/#uses-for-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);
}