You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust Actix中如何解析awc::client返回结果为JSON并读取字段

实现方案

首先需要在Cargo.toml中添加JSON解析依赖:

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

方式1:强类型解析(推荐,类型安全)

先根据返回的JSON结构定义对应结构体,实现序列化trait:

use serde::Deserialize;

// 结构体字段和JSON字段一一对应
#[derive(Deserialize, Debug)]
struct TraceResponse {
    matchings: Vec<serde_json::Value>, // 可根据实际元素类型替换Value
    tracepoints: Vec<serde_json::Value>, // 可根据实际元素类型替换Value
}

修改请求代码,直接用awc自带的json()方法解析响应,无需手动读取body:

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

// 解析响应为指定结构体,直接获取tracepoints字段
let trace_resp: TraceResponse = response.unwrap().json().await.unwrap();
let tracepoints = trace_resp.tracepoints;
println!("tracepoints: {:?}", tracepoints);

方式2:动态解析(无需定义结构体)

如果不想提前定义结构体,可以直接解析为动态Value类型读取字段:

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

// 解析为动态JSON对象
let resp_json: serde_json::Value = response.unwrap().json().await.unwrap();
// 读取tracepoints字段,兼容字段不存在的场景
let tracepoints = resp_json.get("tracepoints")
    .and_then(|v| v.as_array())
    .unwrap_or_default();
println!("tracepoints: {:?}", tracepoints);

基于你现有代码的改造方案

如果你已经手动读取了body数据,可以直接从body二进制内容解析:

let bodydata = response.unwrap().body().await.unwrap();
// 从二进制body解析JSON
let resp_json: serde_json::Value = serde_json::from_slice(&bodydata).unwrap();
let tracepoints = resp_json.get("tracepoints").unwrap();

注意:以上示例使用unwrap仅为简化代码,生产环境请针对请求失败、JSON解析失败、字段不存在等场景做对应错误处理,避免程序panic。

内容的提问来源于stack exchange,提问作者Pamungkas Jayuda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:36:03