title | timestamp | author | published | description | tags | todo | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Read simple JSON and deserialize into a struct |
2023-12-01 03:30:01 -0800 |
szabgab |
true |
Deserializing a JSON string is not too hard especially if the JSON is simple and if we don't need all the fields. |
|
|
In another post we saw how to process arbitrary JSON string without defining anything about it and without creating a struct. It can be a good idea when we start experimenting with a new JSON structure, but eventually we will want to create a struct and deserialize the JSON string into this struct.
In this example we start on that journey for a simple JSON File that looks like this:
{% include file="examples/read-simple-json/data.json" %}
For this we'll need both serde_json and serde with the derive feature.
{% include file="examples/read-simple-json/Cargo.toml" %}
{% include file="examples/read-simple-json/src/main.rs" %}
We need to create a struct to represent the data where we define the expected fields and their type.
As our real data does not have a lot of fields we could have created a struct defining all the fields, but I wanted to show the process you might take if you have a bigger JSON file and don't want to do all the work up-front, or if you don't actually need all the fields from the JSON string.
struct Person {
fname: String,
married: bool,
}
We need to add the Deserialize trait to it. I also included the Debug trait to allow us to use the dbg! macro to display the content of the struct.
#[derive(Deserialize, Debug)]
The we open the file and use the serde_json::from_reader function to read in the file.
serde_json::from_reader(&file).expect("JSON parsing error")
The important part that differs from the generic JSON parsing example is
that we read the data into a variable that was annotated with the Person
struct:
let data: Person =
The we can use the dbg!
macro to show the content of the struct. We also use the
assert_eq! to verify the value of a
string and the assert! macro to verify the
value of a bool
(boolean) field.
It is quite easy to get started deserializing a simple JSON file, especially if we don't need to get all the fields right at the beginning.
There are, however many more aspect of JSON we need to deal with.
- How to handle more complex JSON structures?
- How to handle a JSON that has a list (array) at the root?
- How can we make sure we mapped all the fields?
- What to do if a field we added to the struct is missing from the JSON?
- What to do if there is a typo in the fields of the JSON?