Harry
Harry

Reputation: 2954

serde through an error for unintended field

How to make serde through an error if the json string contains an extra field. This is my code

#[derive(Debug, serde::Deserialize)]
struct C {
    a: A,
    b: B,
}

#[derive(Debug, serde::Deserialize)]
struct A {
    i: i32,
}

#[derive(Debug, serde::Deserialize)]
struct B {
    f: f64,
}

fn main() {
    let json_string = r#"
        {
            "a": {
                "i": 32
            },
            "b": {
                "f": 3.4
            },
            "c": {
                "s": "ftree"
            }
        }
    "#;
    
    // this is getting successfully de-serialized even if the json string contains an extra field "c", a case in which I would like an error to be reported
    if let Ok(res) = serde_json::from_str::<C>(json_string) {
        println!("successfully parsed");
    }
}

Upvotes: 1

Views: 52

Answers (1)

zinderud
zinderud

Reputation: 63

try

#[derive(Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct C {
    a: A,
    b: B,
}

#[derive(Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct A {
    i: i32,
}

#[derive(Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct B {
    f: f64,
}

fn main() {
    let json_string = r#"
        {
            "a": {
                "i": 32
            },
            "b": {
                "f": 3.4
            },
            "c": {
                "s": "ftree"
            }
        }
    "#;
    
    // This will now result in a deserialization error
    match serde_json::from_str::<C>(json_string) {
        Ok(_) => println!("successfully parsed"),
        Err(e) => println!("Error parsing JSON: {}", e),
    }
}

Upvotes: 0

Related Questions