Member-only story

Rust

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.

Donald Le

--

Photo by W on Unsplash

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:

auth_resource_path: String,
field: String,
id: String,
project_id: String,
type: String,
value: String,

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?;

--

--

No responses yet