如果 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");
}
}
尝试
#[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),
}
}