Rust Lesson 56 – Serialization | Dataplexa

Serialization in Rust

In this lesson, you will learn what serialization is and how Rust converts data into formats that can be stored or transmitted over a network.

Serialization is essential for networking, file storage, APIs, and data exchange between systems.


What Is Serialization?

Serialization is the process of converting a data structure into a format that can be saved or sent, such as JSON or binary.

Deserialization is the reverse process — converting that data back into a usable program structure.


Why Serialization Is Important

Serialization is commonly used for:

  • Sending data over a network
  • Storing structured data in files
  • Building REST APIs
  • Saving application state

Rust uses powerful libraries to make serialization safe and efficient.


The Serde Library

The most popular serialization framework in Rust is Serde.

Serde allows you to serialize and deserialize Rust data structures with minimal code.

Add the following dependencies to your Cargo.toml file:

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

Defining a Serializable Struct

To serialize a struct, you must derive the Serialize and Deserialize traits.

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct User {
    id: u32,
    name: String,
    active: bool,
}

This struct is now ready for serialization and deserialization.


Serializing to JSON

You can convert a Rust struct into JSON using serde_json.

use serde_json;

fn main() {
    let user = User {
        id: 1,
        name: String::from("Alice"),
        active: true,
    };

    let json = serde_json::to_string(&user).unwrap();
    println!("{}", json);
}

This produces a JSON string representation of the struct.


Deserializing from JSON

You can convert JSON data back into a Rust struct.

use serde_json;

fn main() {
    let data = r#"{"id":1,"name":"Alice","active":true}"#;

    let user: User = serde_json::from_str(data).unwrap();
    println!("User name: {}", user.name);
}

Serde ensures type safety during deserialization.


Working with Files

Serialized data is often stored in files.

use std::fs;

fn main() {
    let user = User {
        id: 2,
        name: String::from("Bob"),
        active: false,
    };

    let json = serde_json::to_string_pretty(&user).unwrap();
    fs::write("user.json", json).unwrap();
}

This saves the serialized data into a file.


Common Serialization Formats

Rust supports many formats through Serde:

  • JSON
  • YAML
  • TOML
  • Bincode (binary)

Each format is suited for different use cases.


Error Handling in Serialization

Serialization can fail due to invalid data or mismatched types.

Always handle errors properly instead of using unwrap() in production.


📝 Practice Exercises


Exercise 1

Create a struct representing a product and serialize it to JSON.

Exercise 2

Deserialize JSON data back into a struct.

Exercise 3

Save serialized data to a file and read it back.


✅ Practice Answers


Answer 1

#[derive(Serialize, Deserialize)]
struct Product {
    id: u32,
    name: String,
    price: f64,
}

Answer 2

let json = r#"{"id":1,"name":"Laptop","price":999.99}"#;
let product: Product = serde_json::from_str(json).unwrap();

Answer 3

Use fs::write and fs::read_to_string with Serde.


What’s Next?

In the next lesson, you will learn about Logging in Rust and how to monitor application behavior effectively.