jsonrustreqwest

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


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?


Solution

  • 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"