【问题标题】:How can an arbitrary json structure be deserialized with reqwest get in Rust?如何在 Rust 中使用 reqwest 反序列化任意 json 结构?
【发布时间】:2020-09-13 16:20:23
【问题描述】:

我对 rust 完全陌生,我正在尝试找出如何从 URL 端点加载反序列化任意 JSON 结构。

reqwest README 中的相应示例如下所示:

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(())
}

因此,在本例中,目标结构——即以字符串为键、字符串为值的 HashMap 对象——显然是已知的。

但是,如果我不知道在请求端点上收到的结构是什么样的呢?

【问题讨论】:

    标签: json rust reqwest


    【解决方案1】:

    您可以使用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(())
    }
    

    您必须将serde_json 添加到您的 Cargo.toml 文件中。

    [dependencies]
    ...
    serde_json = "1"
    

    【讨论】:

      最近更新 更多