What I mean by that is the following:
Given this struct:
struct SomeObj {
someProp: bool
}
Is there a way to force Serde to assign true / false to someProp when its value is NOT boolean in the JSON input?
Normally, serde would just return an error in such cases (invalid type, expected XY..etc). But would it be possible to suppress the error and just provide some meaningful default value instead?
I know this is possible doing something like:
#[serde(from = "serde_json::Value")]
struct SomeObj {
someProp: bool
}
impl From<serde_json::Value> for SomeObj {
...
}
But there there are a huge number of complex and large structs I need to deal with, so handling this globally would be much easier.
You can always override
serde's choice of deserializer with the attributedeserialize_with. This attribute accepts a function that will be used to deserialize, in place of the usualDeserializetrait.You just need to attach that
deserialize_withattribute to every field that you want the custom defaulting behavior on.If you're willing to pull in an extra dependency, the
serde_withlibrary hasDefaultOnError, which returns theDefault::default()value for a type (that'sfalse,"",0,0.0, etc.) if any deserialization error occurs on that field. So with that structure, you can mark any field as#[serde_as(deserialize_as = "DefaultOnError")]and, provided the underlying type implements the traitDefault, it'll just work.This will work on
bool, any signed or unsigned integer type, floating-point types, strings, and anything that satisfiesDefault.