Parse json to data structures in Rust
Parse json to object or list of objects is done a little bit differently when compared to other languages like Go or Java.
For example we want to get json() return type from the Http API, we have to define the data structures of the json response accordingly. Let’s say the response from API is a list of object which contains the following fields:
Then we must define the struct type for this object.
Notice that in the field of object we have “type” which is one of the restricted keyword in Rust.
In this case, we can use serd to rename the field to type
#[serde(rename = "type")]
The json value consist a list of objects, so we use the type Vector of object.
let json_value: Vec<SearchElement> = res.json().await?;
The complete main function for parse json value look like this:
Hope it helps.