I want to make sure certain fields are NOT specified when deserializing. I want to throw an error during deserialization if the field is present. Note that I am not asking about the field being None
. I am asking about making sure the field itself isn't specified.
I asked ChatGPT and it gave me the following:
#[derive(Deserialize)]
struct MyStruct {
#[serde(default, deserialize_with = "check_field")]
required_field: Option<String>,
other_field: String,
}
fn check_field<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
if deserializer.is_human_readable() {
// If deserialization is happening from a human-readable format, throw an error
Err(serde::de::Error::custom("Required field should not be present"))
} else {
// If deserialization is happening from a non-human-readable format, proceed normally
Ok(None)
}
}
While this does seem to work, I am not sure if deserializer.is_human_readable()
is the right way? I read the documents and it says the following:
"Some types have a human-readable form that may be somewhat expensive to construct, as well as a binary form that is compact and efficient. Generally text-based formats like JSON and YAML will prefer to use the human-readable one and binary formats like Postcard will prefer the compact one."
So this doesn't seem right as if the field is in binary form, then it would allow it to exist.
Is there a better/correct way?