JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.76k stars 3.25k forks source link

PopulateObject won't throw Exception on invalid JSON #2924

Open arnaudgout opened 9 months ago

arnaudgout commented 9 months ago

EDIT: adding CheckAdditionalContent = true in the settings make the PopulateObject throw for this case, but it's still confusing that both methods won't have the same default behavior

Source/destination types

class Test
{
    public int test;
}

Source/destination JSON

"{\"test\":1}gg"

Expected behavior

Should throw JsonReaderException

Actual behavior

Will deserialize the proper value. (Test.test == 1)

Steps to reproduce

// here is a test case that fails in the last step
[Test]
public void PopulateObjectInvalidJson()
{
    Assert.Throws(typeof(JsonReaderException), () =>
    {
        var o = JsonConvert.DeserializeObject<Test>("{\"test\":1}invalidtrailingchar");
    });   // will pass
    Assert.Throws(typeof(JsonReaderException), () =>
    {
        var o = new Test() { test = 0 };
        JsonConvert.PopulateObject("{\"test\":1}invalidtrailingchar", o);
    });   // will fail here
}

class Test
{
    public int test;
}