我正在使用reqwest执行来自https://httpbin.org的GET请求。对像https://httpbin.org/ip这样的一级json端点执行请求很容易。
use std::collections::HashMap;
fn main() {
let body = reqwest::blocking::get("https://httpbin.org/ip")
.unwrap()
.json::<HashMap<String, String>>()
.unwrap();
dbg!(body);
}然而,我不知道如何使用多级别的JSON响应来处理其他端点。如何向reqwest中的多级JSON端点发出请求
use std::collections::HashMap;
fn main() {
let body = reqwest::blocking::get("https://httpbin.org/get")
.unwrap()
.json::<HashMap<K, V>>()
.unwrap();
dbg!(body);
}发布于 2022-02-04 04:06:05
正如@BallpointBen建议的那样,反序列化到serde_json::Value中肯定有效。但是在许多情况下,您将需要手动从任意json值中提取数据,这很繁琐。有一种更好的方法:反序列化为锈菌结构:
struct Response { /* … */ }
let body = reqwest::blocking::get("https://httpbin.org/get?arg=blargh")
.unwrap()
.json::<Response>()
.unwrap();要做到这一点,您需要向serde解释如何使用您的结构,例如:
use std::{collections::HashMap, net::IpAddr};
use serde::Deserialize;
#[derive(Deserialize)]
struct Response {
args: HashMap<String, String>,
// I'm making headers into another struct here to show some possibilities. You can of course make it a HashMap like args
headers: ResponseHeaders,
origin: IpAddr,
url: url::Url,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct ResponseHeaders {
accept: String,
host: String,
#[serde(flatten)]
dynamic: HashMap<String, String>,
}反序列化为原生锈菌结构有点像兔子洞,上面有一个小书。
https://stackoverflow.com/questions/70980804
复制相似问题