0

Rust – Convert Struct Instances to and from JSON

In Rust, there is an excellent crate that converts struct  instances to and from JSON.

Cargo.toml

We need to crates for this – serde and serder_json. Update the dependencies section of Cargo.toml to:

Our structs

The structs for our codes are as follow.

We need modify our structs to use serde ‘s Serialize  and Deserialize  traits. The use  statement is required for the two traits to be used.

main.rs

In the main() function, we use serde_json::to_string()  and serde_json::from_str()  functions.

User instance

Consider the following instance of User .

Instance to JSON String

To convert this to JSON, the codes would be:

Output:

JSON String to Instance

Let us use a different JSON string with the same structure:

Output:

Karl San Gabriel

Karl San Gabriel

Professional Software Developer