我试图使用rustc_serialize将JSON反序列化为Rust struct .问题是某些JSON有一些可选字段,即可能存在也可能不存在.遇到第一个缺席字段的时候,解码器似乎跳出,而不考虑后续字段,即使它们存在.有没有办法克服这个问题?
以下是代码:
extern crate rustc_serialize;
#[derive(Debug)]
struct B {
some_field_0: Option<u64>,
some_field_1: Option<String>,
}
impl rustc_serialize::Decodable for B {
fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
Ok(B {
some_field_0: d.read_struct_field("some_field_0", 0, |d| rustc_serialize::Decodable::decode(d)).ok(),
some_field_1: d.read_struct_field("some_field_1", 0, |d| rustc_serialize::Decodable::decode(d)).ok(),
})
}
}
fn main() {
{
println!("--------------------------------\n1st run - all field present\n--------------------------------");
let json_str = "{\"some_field_0\": 1234, \"some_field_1\": \"There\"}".to_string();
let obj_b: B = rustc_serialize::json::decode(&json_str).unwrap();
println!("\nJSON: {}\nDecoded: {:?}", json_str, obj_b);
}
{
println!("\n\n--------------------------------\n2nd run - \"some_field_1\" absent\n---------------------------------");
let json_str = "{\"some_field_0\": 1234}".to_string();
let obj_b: B = rustc_serialize::json::decode(&json_str).unwrap();
println!("\nJSON: {}\nDecoded: {:?}", json_str, obj_b);
}
{
println!("\n\n--------------------------------\n3rd run - \"some_field_0\" absent\n---------------------------------");
let json_str = "{\"some_field_1\": \"There\"}".to_string();
let obj_b: B = rustc_serialize::json::decode(&json_str).unwrap();
println!("\nJSON: {}\nDecoded: {:?}", json_str, obj_b);
}
}
以下是输出:
--------------------------------
1st run - all field present
--------------------------------
JSON: {"some_field_0": 1234, "some_field_1": "There"}
Decoded: B { some_field_0: Some(1234), some_field_1: Some("There") }
--------------------------------
2nd run - "some_field_1" absent
---------------------------------
JSON: {"some_field_0": 1234}
Decoded: B { some_field_0: Some(1234), some_field_1: None }
--------------------------------
3rd run - "some_field_0" absent
---------------------------------
JSON: {"some_field_1": "There"}
Decoded: B { some_field_0: None, some_field_1: None }
请注意,第三次运行会产生意外的结果.当解码器无法找到some_field_0
时,它会在所有后续令牌上失败,即使some_field_1
存在.