Created
December 5, 2014 21:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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