Rust – Convert Struct Instances to and from JSON

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


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.


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:


JSON String to Instance

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


Karl San Gabriel

Karl San Gabriel

Professional Software Developer