Question
Require a field to be an integer or null, but not missing in JSON
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.
5 139
5