Skip to content

Instantly share code, notes, and snippets.

@jroweboy
Created December 5, 2014 21:07
Show Gist options
  • Save jroweboy/ba6822ea59398c1ecb35 to your computer and use it in GitHub Desktop.
Save jroweboy/ba6822ea59398c1ecb35 to your computer and use it in GitHub Desktop.
A sample custom decoder implementation that I wrote back in July. Still compiles, but it could be cleaner I guess
extern crate serialize;
use serialize::json;
use serialize::json::{DecodeResult, DecoderError, UnknownVariantError, MissingFieldError};
use serialize::{Decoder, Decodable};
#[deriving(Show)]
pub struct Test {
recipe_id: int,
type_: String,
}
impl<D: Decoder<DecoderError>> Decodable<D, DecoderError> for Test {
fn decode(d: &mut D) -> DecodeResult<Test> {
d.read_map(|e: &mut D, len: uint| -> DecodeResult<Test> {
let mut recipe_id = None;
let mut type_ = None;
let mut count = 0;
while count < len {
match e.read_str() {
Ok(s) => {
match s.as_slice() {
"recipe_id" => {
recipe_id = match e.read_int() {
Ok(o) => Some(o),
Err(e) => { return Err(e); }
};
},
"type" => {
type_ = match e.read_str() {
Ok(o) => Some(o),
Err(e) => { return Err(e); }
};
},
_ => { return Err(UnknownVariantError("Extra field found".to_string())); },
}
},
Err(e) => {return Err(e);},
}
count += 1;
}
if type_.is_none() {
Err(MissingFieldError("Missing Type Field".to_string()))
} else if recipe_id.is_none() {
Err(MissingFieldError("Missing Recipe Id Field".to_string()))
} else {
Ok(Test {
recipe_id: recipe_id.unwrap(),
type_: type_.unwrap(),
})
}
})
}
}
fn main() {
let t : Test = match json::decode::<Test>("{\"type\": \"Hello!\", \"recipe_id\": 3}".as_slice()) {
Ok(o) => o,
Err(e) => {println!("{}", e); panic!();},
};
println!("{}", t);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment