Skip to content

Instantly share code, notes, and snippets.

@kejadlen
Created August 29, 2017 02:07
Show Gist options
  • Save kejadlen/7a72d140e6909788af14b9ba83cf2982 to your computer and use it in GitHub Desktop.
Save kejadlen/7a72d140e6909788af14b9ba83cf2982 to your computer and use it in GitHub Desktop.
Custom deserialization of JSON w/Serde
fn deserialize_images<'de, D>(de: D) -> Result<Vec<Image>, D::Error>
where D: serde::Deserializer<'de>
{
let value: serde_json::Value = serde::Deserialize::deserialize(de)?;
let object = value
.as_object()
.ok_or(serde::de::Error::custom("expected an object of images"))?;
let images = object
.iter()
.flat_map(|(k, v)| match (k.as_ref(), v) {
("original", &serde_json::Value::Object(ref map)) => {
map.get("url")
.and_then(|v| v.as_str())
.and_then(|s| Url::parse(s).ok())
.map(|url| Image::Original(url))
}
("fixed_width_small_still", &serde_json::Value::Object(ref map)) => {
map.get("url")
.and_then(|v| v.as_str())
.and_then(|s| Url::parse(s).ok())
.map(|url| Image::Thumbnail(url))
}
_ => None,
})
.collect();
Ok(images)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment