简体   繁体   中英

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. 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 . 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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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