Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// serde = "1.0"
// serde_derive = "1.0"
// serde_json = "1.0"
use serde::{Deserialize, Deserializer};
use serde_derive::Deserialize;
#[derive(Debug, Deserialize)]
struct Hoge {
#[serde(deserialize_with="deserialize_option")]
val: Option<u64>,
}
// deny if entry is not exist
// (null is acceptable)
fn deserialize_option<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where D: Deserializer<'de>,
T: Deserialize<'de>
{
Deserialize::deserialize(deserializer)
}
fn main() {
let json_1 = r#"{ "val": 334 }"#;
let ans_1: Hoge = serde_json::from_str(json_1).unwrap();
assert_eq!(ans_1.val, Some(334));
let json_2 = r#"{ "val": null }"#;
let ans_2: Hoge = serde_json::from_str(json_2).unwrap();
assert_eq!(ans_2.val, None);
let json_3 = r#"{}"#;
let ans_3: Result<Hoge, _> = serde_json::from_str(json_3);
assert!(ans_3.is_err());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment