fn get_results() -> Option<Json> {
// ...
let json = &Json::from_str(&body).unwrap();
return match json.as_object().unwrap().get("results") {
Some(obj) => Some(obj.clone()),
_ => None
}
}
- We cannot
return json.as_object().unwrap().get("results")
since it's aOption<&Json>
- The way above is derp
Solution:
let json = &Json::from_str(&body).unwrap();
return json.as_object().unwrap()
.get("results").map(|r| r.clone());
If you need (de)serialization (both json and xml), use the rustc-serialize crate.
Push on (de)serializing data using struct
s. Decodable
works even with struct
s containing other collections of struct
s
rust-lang-deprecated/rustc-serialize#112
CLI's args are 0-indexed ([0] is the executable's path), so you need to check if args().collect().len() > 1
Decoder
is smart enough to match the nearest json fields with the respective given string.
decoder.read_struct("root", 0, |decoder| {
Ok(Image {
size: try!(decoder.read_struct_field("size", 0, |decoder| Decodable::decode(decoder))),
url: try!(decoder.read_struct_field("#text", 0, |decoder| Decodable::decode(decoder)))
})
})
The code above works fine even if size
and #text
are nested from the root.
If you want to share your macros through the modules, put them in macros.rs
and import it before any other module with
#[macro_use]
mod macros
decoder.read_struct_field("size", 0, |decoder| Decodable::decode(decoder)
is the same of
decoder.read_struct_field("size", 0, Decodable::decode