Rust, Software Development

Rust – Convert Struct Instances to and from JSON

Rust lang Convert Struct JSON

In Rust, there are two excellent crates that can convert struct instances to and from JSON. These are perfect for creating RESTful APIs that consume and produce JSON content. These are serde and serde_json crates.

Use Rust Crates In Cargo.toml

If we need to use these crates, we update our Cargo.toml as follows.

Let’s Start With Some Rust structs

The structs for our codes are as follows.

We need to modify our structs to use serde’s Serialize and Deserialize traits. We use statement import these two traits into our codes so that we can use them.

Rust Code To Convert Struct Instances To JSON

In the main function, we use serde_json::to_string()  and serde_json::from_str()  functions. Consider the following instance of User.

Given this struct instance, we can convert it to JSON using the following codes.

The codes generate the following output. Notice that the output contains nested JSON data because our struct User has a property user_person of Person struct type.

Now given the JSON data, how do we convert it to a Rust struct instance? Let us use a different JSON string with the same structure.

When we run the codes, we get the following output.

And that is how we can convert a struct instance to JSON and vice-versa.

You Might Also Like