【问题标题】:How to convert actix_web::web::Bytes to json?如何将 actix_web::web::Bytes 转换为 json?
【发布时间】:2021-04-09 08:46:06
【问题描述】:

这是我的代码:

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let mut client = Client::default();

    // Create request builder and send request
    let response = client
        .get("https://ipapi.co/localhost/json")
        .header("User-Agent", "actix-web/3.0")
        .send() // <- Send request
        .await; // <- Wait for response
    let result = response.unwrap().body().await.unwrap();
    println!("Response: {:?}", result);


}

此代码有效,但我不知道如何将类型 actix_web::web::Byte 转换为 json。

我已尝试将其转换为 ti json:

    let result = response
        .unwrap()
        .json::<HashMap<String, std::marker::PhantomData<String>>>()
        .await;

但是每次我收到一个错误,因为 HashMap 有混合类型。它是 HashMap。

所以我的问题是:

如何将响应转换为 json?

我正在使用use actix_web::client::Client。

【问题讨论】:

    标签: json rust actix-web


    【解决方案1】:

    您可以使用serde_json::value::Value

    use serde_json::value::Value;
    
    ...
    
    let result = response
            .unwrap()
            .json::<HashMap<String, Value>>()
            .await;
    

    【讨论】:

    • 另外,定义一个 precise 可反序列化的结构,这样每个值都匹配到正确键入的字段,而不必将所有内容转储到哈希图中。
    猜你喜欢
    • 1970-01-01
    • 2022-07-26
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多