小编Sam*_*ena的帖子

使用 actix_web 对部分结构进行 Serde 反序列化

我有一个 API 端点,actix_web用于反序列化传入的 JSON 有效负载(actix_web最终serde用于 JSON 反序列化)。

例如,我有一些看起来像这样的东西:

pub struct IncomingPayload {
    pub field1: i32,
    pub field2: String
}

pub async fn update_platforms(
    pool: web::Data<Pool>,
    req: web::Json<Vec<IncomingPayload>>,
) -> Result<HttpResponse, error::Error> { 
    println!(req.field1); // will be an i32
    println!(req.field2); // will be a String
}
Run Code Online (Sandbox Code Playgroud)

目前,只有serde能够反序列化结构的所有字段,此端点才会成功返回。即一个请求必须包含field1field2键。

例如,这将是成功的:

curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"field1": 1,"field2":"something"}' \
  http://localhost:8080
Run Code Online (Sandbox Code Playgroud)

但这不会(因为field2有效载荷中缺少):

curl --header "Content-Type: application/json" \ …
Run Code Online (Sandbox Code Playgroud)

json rust serde rust-actix actix-web

1
推荐指数
1
解决办法
852
查看次数

标签 统计

actix-web ×1

json ×1

rust ×1

rust-actix ×1

serde ×1