Unable to tackle optional fields in JSON with Rustc-serialize Unable to tackle optional fields in JSON with Rustc-serialize json json

Unable to tackle optional fields in JSON with Rustc-serialize


There's something wrong with your Decodable implementation. Using the automatically-generated implementation works:

#[derive(Debug, RustcDecodable)]struct B {    some_field_1: Option<String>,    some_field_0: Option<u64>,}
JSON: {"some_field_1": "There"}Decoded: B { some_field_1: Some("There"), some_field_0: None }

Using the generated implementation is the right thing to do if you can. If you cannot, here's the right implementation:

impl rustc_serialize::Decodable for B {    fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {        Ok(B {            some_field_0: try!(d.read_struct_field("some_field_0", 0, |d| rustc_serialize::Decodable::decode(d))),            some_field_1: try!(d.read_struct_field("some_field_1", 0, |d| rustc_serialize::Decodable::decode(d))),        })    }}

The important change is the use of try!. Decoding can fail. By using ok, you were saying that a failed decoding was actually a success, albeit a successful decoding of a None.