I want to deserialize the following struct using serde_json. The parent_id
field should accept an integer or a null, but I want it to return an error if the field is missing.
#[derive(Debug, Serialize, Deserialize)]
pub struct Group {
pub name: String,
pub parent_id: Option<i32>,
}
// this is accepted
serde_json::from_value(json!({
"name": "Group 1",
"parent_id": null,
});
// this should return an error
serde_json::from_value(json!({
"name": "Group 1",
});
I tried using the code above, but parent_id
would be deserialized into a None
even though it doesn't exist.
Type::deserialize
implementation to do it. But this works becauseOption<_>
is special-cased by serde with#[serde(default)]
because its often intended to handle missing values. However, adding thedeserialize_with
skips that special-casing so that it no longer defaults toNone
(and therefore complain when missing). – Diandre