如何使用reqwest对任意json结构进行反序列化,使其进入Rust?

问题描述

我完全不熟悉rust,我试图找出如何从URL端点重新加载反序列化任意JSON结构的方法

reqwest自述文件中的相应示例如下:

<html>
  <body>
    <h3>img tag:</h3>
    <div class="container">
      <img src="https://via.placeholder.com/150x150" alt="">
    </div>
    
    <h3>picture tag:</h3>
    <div class="container">
      <picture>
        <source srcset="https://via.placeholder.com/184x184" media="(min-width: 400px)" />
        <img src="https://via.placeholder.com/50x50" alt="">
      </picture>
    </div>
    <div class="container">
      <picture>
        <source srcset="https://via.placeholder.com/150x150" media="(min-width: 400px)" />
        <img src="https://via.placeholder.com/100x100" alt="">
      </picture>
    </div>
  </body>
</html>

因此,在本示例中,目标结构(即具有字符串作为键和值为值的字符串的HashMap对象)显然是已知的。

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

解决方法

您可以使用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"