Parsing Json in Rust easily from API call
Tags: rust, api, beginners, programming
Published: 2022-06-07 10:26:52


JSON has become one of the most popular data interchange formats on the web, thus it's vital that server-side languages handle it well.
Actually OpenAPI specification also use JSON format.
Fortunately, working with JSON is an area where Rust excels, owing in large part to the serde and serde json crates.
When compared to other languages such as Python or Java, parsing JSON to object or list of objects is done slightly differently.

In this article I will explain how to work with JSON. I will use the previous API I wrote, check my [previous article](https://dev.to/nathan20/build-your-first-api-with-rust-5da5) before continue.


## How to use serde_json?
First of all, your dependencies should looks like this:

```
[dependencies]
rocket = "0.4.11"
rocket_codegen = "0.4.11"
http = "0.2"
reqwest = { version = "0.11", features = ["blocking","json"] }

serde = { version = "1", features = ["derive"] }
serde_json = "1"

```

To begin, you must add the Serialize and Deserialize traits on your type. To use [derive macros](https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros) check if the derive: feature is enabled in your dependencies.
Here I use a method called ORM (Object–relational mapping) that consists to converts data between type systems. 
My Coin  structure looks like this with derive marco. On each type you have to declare this traits on your type.


```
#[derive(Debug, Deserialize, Serialize)]
struct Coin {
    id: String,
    symbol: String,
    market_data: MarketData
}

```



I define the other struct depending on what I need based on the given JSON. 

```
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
struct CurrentPrice {
    usd: i64
}
#[derivedestruct(Debug, Deserialize, Serialize)]

struct MarketData {
    pub current_price: CurrentPrice
}
```

## Let's dive into the code

After sending the request to backend-api , if the status code is success, then I try to deserialize the response body using serde then saved my JSON response in the "json_value" variable.   


```
    let json_value = resp.json::<Coin>();
        match json_value {
            Ok(value)=>{
                println!("{:?}", value.id);
                Ok(format!(" Coin:{} Symbol:{} price:{:?}" ,value.id, value.symbol,  value.market_data.current_price.usd))  
        }
        Err(value) => { Ok(format!("value{:?}",value))}
       
    }
    }
    else{
        let response = resp.text().unwrap();
        Ok(format!("{} is not a coin!", response))
    }
```
The "json_value" variable is "Result" type so I need to unwrap it in order to get the Coin Object.
I used match then I print the desired data on the HTML page with the help of format.

This is the final result:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s20z5ugs858msms4g9zr.png)

I finished a series of small and simple articles about API in a Rust context. I will wrote a more advanced article in the near future.

Between this you can check our API Solution at [www.blstsecurity.com](https://www.blstsecurity.com/?promo=blst&domain=https://nathan.devto3).

If you are interested in more topic related to Rust join our Discord Server: [https://discord.gg/ajDuTJWD](https://discord.gg/ajDuTJWD).