简体   繁体   English

如何将 Rust Actix awc::client 的结果解析为 json 并读取 json 元素

[英]How to parse result from Rust Actix awc::client to json and read json elements

I have request with awc::client, and has respond to Result - body.我有 awc::client 的请求,并已响应 Result - body。 How to read element from that result.如何从该结果中读取元素。

    let response = client.post("http://localhost:8002/trace_route")
        .send_json(&request)
        .await;

    let bodydata = response.unwrap().body().await;
    println!("Response: {:?}", bodydata);

return from that request is该请求的返回是

{
"matchings": [],
"tracepoints": []
}

How i get element tracepoint from that Result.我如何从该结果中获取元素跟踪点。 Thanks anyway不管怎么说,还是要谢谢你

As noted in comments, you need to use reqwest's .json method .正如在评论中指出,需要使用reqwest的.json 方法 Let's look at the method signature,让我们看看方法签名,

pub async fn json<T: DeserializeOwned>(self) -> Result<T>

There are two things to note here:这里有两点需要注意:

  1. Rust is a typed language so the compiler needs to know the type T which specifically is part the return result. Rust 是一种类型化语言,因此编译器需要知道类型T ,它特别是返回结果的一部分。

If I were you I would do如果我是你,我会做

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);

}

You would think this would work but I hope you can guess what.你会认为这会奏效,但我希望你能猜到是什么。

  1. T must implement serde::DeserializeOwned which can easily be handled by a derive. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM