1

I am using a structure to receive data from a http request body in rust. This is the struct define:

use rocket::serde::Deserialize;
use rocket::serde::Serialize;

#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
#[allow(non_snake_case)]
pub struct LearningWordRequest {
    pub wordId: i64,
    pub word: String,
    pub wordStatus: i32
}

but I have to put all of the fields into the body to parse, if I did not do it like that. The server will show:

2021-11-10T15:02:43 [WARN] - `Json < LearningWordRequest >` data guard failed: Parse("{\"word\":\"hood\",\"wordId\":-1}", Error("missing field `wordStatus`", line: 1, column: 27)).

is it possible to make the parse just ignore the field if I did not put this field? Sometimes it is no need to transfer all fields in the http body, this is my server side receive code:

#[post("/v1/add",data = "<record>")]
pub fn add_learning_word(record: Json<LearningWordRequest>) -> content::Json<String> {
    let res = ApiResponse {
        result: "ok",
        ..Default::default()
    };
    let response_json = serde_json::to_string(&res).unwrap();
    return content::Json(response_json);
}
Dolphin
  • 29,069
  • 61
  • 260
  • 539
  • 1
    See also: https://stackoverflow.com/questions/44331037 https://stackoverflow.com/q/44301748 – E_net4 Nov 10 '21 at 15:27

1 Answers1

3

Change the struct member to be optional:

#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
#[allow(non_snake_case)]
pub struct LearningWordRequest {
    pub wordId: i64,
    pub word: String,
    pub wordStatus: Option<i32>
}

For example:

fn main() {
    let present = r#" {
        "wordId": 43,
        "word": "foo",
        "wordStatus": 1337
    }"#;
    let absent = r#" {
        "wordId": 43,
        "word": "foo"
    }"#;

    println!("{:?}", serde_json::from_str::<LearningWordRequest>(present));
    println!("{:?}", serde_json::from_str::<LearningWordRequest>(absent));
}

Outputs:

Ok(LearningWordRequest { wordId: 43, word: "foo", wordStatus: Some(1337) })
Ok(LearningWordRequest { wordId: 43, word: "foo", wordStatus: None })
orlp
  • 112,504
  • 36
  • 218
  • 315