Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to ignore null field in rust web request

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#[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);
}

>Solution :

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 })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading