通过非预期字段的错误进行 Serde

问题描述 投票:0回答:1

如果 json 字符串包含额外字段,如何使

serde
通过错误。这是我的代码

#[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");
    }
}
rust serde
1个回答
0
投票

尝试

#[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),
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.