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.
1 2 3 4 5 6 7 8 9 | [package] name = "struct-json" version = "0.1.0" authors = ["Karl San Gabriel"] edition = "2018" [dependencies] serde = { version = "1.0.126", features = ["derive"] } serde_json = "1.0.64" |
Let’s Start With Some Rust structs
The structs for our codes are as follows.
1 2 3 4 5 6 7 8 9 10 11 | struct Person { person_id: i32, person_name: String } struct User { user_id: i32, user_name: String, user_password: String, user_person: Person } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Person { person_id: i32, person_name: String } #[derive(Serialize, Deserialize, Debug)] struct User { user_id: i32, user_name: String, user_password: String, user_person: Person } |
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.
1 2 3 4 5 6 7 8 9 | let user = User { user_id: 100, user_name: "user100".to_string(), user_password: "hashed password".to_string(), user_person: Person { person_id: 1, person_name: "Karl San Gabriel".to_string() } }; |
Given this struct instance, we can convert it to JSON using the following codes.
1 2 | let serialized_user = serde_json::to_string(&user).unwrap(); println!("{}", serialized_user); |
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.
1 | {"user_id":100,"user_name":"user100","user_password":"hashed password","user_person":{"person_id":1,"person_name":"Karl San Gabriel"}} |
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.
1 2 | let json_string = "{\"user_id\":200,\"user_name\":\"user200\",\"user_password\":\"this-is-a-hashed-password\",\"user_person\":{\"person_id\":2,\"person_name\":\"Lucas\"}}"; let user200: User = serde_json::from_str(&json_string).unwrap(); |
When we run the codes, we get the following output.
1 | User { user_id: 200, user_name: "user200", user_password: "this-is-a-hashed-password", user_person: Person { person_id: 2, person_name: "Lucas" } } |
And that is how we can convert a struct instance to JSON and vice-versa.