如何在 Rust 中使用 reqwest get 反序列化任意 json 结构?
How can an arbitrary json structure be deserialized with reqwest get in Rust?
我完全不熟悉 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 对象——显然是已知的。
但是,如果我不知道请求端点上接收到的结构是什么样的呢?
您可以使用 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"
我完全不熟悉 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 对象——显然是已知的。
但是,如果我不知道请求端点上接收到的结构是什么样的呢?
您可以使用 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"