Newtonsoft.Json icon indicating copy to clipboard operation
Newtonsoft.Json copied to clipboard

MissingMemberHandling.Error doesn't throw when get-only property is matched

Open strawd opened this issue 5 years ago • 1 comments

Source/destination types

class ImmutableType
{
    public ImmutableType(string wrongName)
    {
        CorrectName = wrongName;
    }

    public string CorrectName { get; }
}

Source/destination JSON

{"correctName":"test"}

Expected behavior

Since there is no constructor parameter and no writable property with the name "correctName", I would expect that MissingMemberHandling.Error would direct Json.NET to throw a JsonSerializationException for the payload.

Actual behavior

No exception is thrown, and the constructor parameter wrongName receives a default value of null. The value passed in "correctName" in the payload is not used. This leads to subtle issues if a constructor argument is misnamed or misspelled.

Steps to reproduce

var serializerSettings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error };
var json = "{\"correctName\":\"test\"}";
var obj = JsonConvert.DeserializeObject<ImmutableType>(json, serializerSettings);

strawd avatar Jan 24 '20 00:01 strawd

I just ran into this issue as well and spent a fair amount of time until I figured it out. It would be great if Json.NET would throw an exception in such a case.

craffael avatar Apr 17 '23 15:04 craffael