Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can an arbitrary json structure be deserialized with reqwest get in Rust?

Tags:

json

rust

reqwest

I am totally new to rust and I am trying to find out how to I can doload an deserialize a arbitrary JSON structure from a URL endpoint.

The respective example on the reqwest README goes like this:

use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resp = reqwest::get("https://httpbin.org/ip")
        .await?
        .json::<HashMap<String, String>>()
        .await?;
        println!("{:#?}", resp);
    Ok(())
}

So in case of this example, the target structure – i.e. a HashMap Object with strings as keys and strings as values – is obviously known.

But what if I don't know what is the structure received on the request endpoint looks like?

like image 559
LongHike Avatar asked Sep 13 '20 16:09

LongHike


1 Answers

You can use serde_json::Value.

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resp = reqwest::get("https://httpbin.org/ip")
        .await?
        .json::<serde_json::Value>()
        .await?;
    println!("{:#?}", resp);
    Ok(())
}

You will have to add serde_json to your Cargo.toml file.

[dependencies]
...
serde_json = "1"
like image 174
Ross MacArthur Avatar answered Nov 01 '22 21:11

Ross MacArthur