I have an object with one constructor that has a parameter name that does not match the property name. Because the parameter name doesn't match, Newtonsoft deserializes it to an object with the default value. I get why that happens and I know I can fix it by changing the parameter name or by making the property { get; set; }
, but I'm surprised that MissingMemberHandling.Error
does not catch the issue. Is there another setting that will cause this to throw an exception?
using Newtonsoft.Json;
// Runnable in LINQPad
void Main()
{
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MissingMemberHandling = MissingMemberHandling.Error;
// Expected: throw an exception
var foo = Newtonsoft.Json.JsonConvert.DeserializeObject<Foo>("{a:123,c:456}", settings);
// Actual: foo.A is 0 and C is 456
Console.WriteLine(foo);
}
public class Foo
{
public Foo(int b, int c)
{
A = b;
C = c;
}
[JsonProperty(Required = Required.Always)]
public int A { get; }
public int C { get; }
}