![](/img/trans.png)
[英]How do I extract path parameters and parse JSON body from the same request using Actix-Web
[英]How to parse result from Rust Actix awc::client to json and read json elements
我有 awc::client 的請求,並已響應 Result - body。 如何從該結果中讀取元素。
let response = client.post("http://localhost:8002/trace_route")
.send_json(&request)
.await;
let bodydata = response.unwrap().body().await;
println!("Response: {:?}", bodydata);
該請求的返回是
{
"matchings": [],
"tracepoints": []
}
我如何從該結果中獲取元素跟蹤點。 不管怎么說,還是要謝謝你
正如在評論中指出,需要使用reqwest的.json
方法。 讓我們看看方法簽名,
pub async fn json<T: DeserializeOwned>(self) -> Result<T>
這里有兩點需要注意:
T
,它特別是返回結果的一部分。如果我是你,我會做
struct Trace {
matchings: Vec<String>,
tracepoints: Vec<String>,
}
fn main() {
let response = client.post("http://localhost:8002/trace_route")
.send_json(&request)
.await;
let bodydata = response.unwrap().json::<Trace>().await;
println!("Response: {:?}", bodydata);
}
你會認為這會奏效,但我希望你能猜到是什么。
T
必須實現serde::DeserializeOwned
,它可以由派生輕松處理。// This `derive` requires the `serde` dependency.
#[derive(Deserialize)]
struct Trace {
matchings: Vec<String>,
tracepoints: Vec<String>,
}
fn main() {
let response = client.post("http://localhost:8002/trace_route")
.send_json(&request)
.await;
let bodydata = response.unwrap().json::<Trace>().await;
println!("Response: {:?}", bodydata);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.