I'm deserializing a bunch of C# readonly structures (which have their constructors marked by [JsonConstructor]), and I'm trying to fail early if any JSON that I receive is malformed.
Unfortunately, if there is a naming discrepancy between the constructor parameter and the input JSON, the parameter just gets assigned a default value. Is there a way that I could get an exception instead, so these defaults don't accidentally "pollute" the rest of my business logic? I have tried playing with various JsonSerializerSettings but to no avail.
Simplified example:
public readonly struct Foo {
[JsonConstructor]
public Foo(long wrong) {
FooField = wrong;
}
public readonly long FooField;
}
public void JsonConstructorParameterTest() {
// The Foo constructor parameter name ("wrong") doesn't match the JSON property name ("FooField").
var foo = JsonConvert.DeserializeObject<Foo>("{\"FooField\":42}");
// The foo.FooField is now 0.
// How can we cause the above to throw an exception instead of just assigning 0 to Foo.FooField?
}
The above can be fixed by renaming wrong into fooField, but I'd like to know that before 0 has already been committed to my database.