Data serialization and deserialization

When it comes to data serialization and deserialization in Rust, there is no doubt we are talking about serde (https://crates.io/crates/serde). Serde, from serialization and deserialization, gives us a unique tool to be able to transform our data structures to JSON, TOML, XML, or any other serializable format. Let's see how it works.

We start with a simple structure:

struct MyData {    field1: String,    field2: u32,    field3: Vec<u8>,}

And we add serde and serde_derive as dependencies to our Cargo.toml file:

[dependencies]serde = "1.0.0"serde_derive = "1.0.0"

Then, in our main.rs file, we just need to import the crates using extern crate and derive the Serialize trait for our structure:

extern crate serde; ...

Get Rust High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.