Skip to content

Instantly share code, notes, and snippets.

@shahn
Created April 2, 2016 14:36
Show Gist options
  • Save shahn/32fa57a6fd1f2e3b3224b3e925308960 to your computer and use it in GitHub Desktop.
Save shahn/32fa57a6fd1f2e3b3224b3e925308960 to your computer and use it in GitHub Desktop.
# This macro is annoying
macro_rules! try_conv {
($expr:expr) => (match $expr {
Ok(val) => val,
Err(err) => {
return Err(SerdeError::custom(err.description()))
}
})
}
impl serde::Deserialize for Foo {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: serde::Deserializer
{
let value: Value = try!(Value::deserialize(deserializer));
// XXX find a solution to get rid of this clone
if let Some(ref s) = value.clone().find("classtype") {
use serde_json::from_value;
if !s.is_string() {
return Err(SerdeError::custom("non-string 'classtype'"))
}
match s.as_string().unwrap() {
"stuff" =>
Ok(Foo(try_conv!(from_value(value)))),
_ => Err(SerdeError::custom("invalid"))
}
} else {
Err(SerdeError::missing_field("classtype"))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment