JamesNK / Newtonsoft.Json

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

Deserializing with `NullValueHandling.Ignore` for a type with constructor parameters doesn't ignore null values #2954

Open ker1o opened 2 months ago

ker1o commented 2 months ago

Source/destination types

class A {
    public A(int arg) {
        }

    public int field;
}

Source/destination JSON

{"arg": 1, "field": null}

Expected behavior

When new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore } is provided field property is initialized with default value for int type

Actual behavior

Unhandled exception. Newtonsoft.Json.JsonSerializationException: Error converting value {null} to type 'System.Int32'. Path 'field'

Steps to reproduce

using Newtonsoft.Json;

public class Program
{
    class A {
        public A(int arg) {
        }

        public int field;
    }

    public static void Main()
    {
        var result = JsonConvert.DeserializeObject<A>("{\"arg\": 1, \"field\": null}", new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
    }
}
ranistar commented 1 month ago

The NullValueHandling.Ignore only working for Serialize not Deserialize. I would suggest to use a Nullable int: public int? field; and judge the value before using: if(field.HasValue)

elgonzo commented 1 month ago

@ranistar

The NullValueHandling.Ignore only working for Serialize not Deserialize.

That is entirely incorrect. The issue report is valid - it's an actual bug/quirk with Newtonsoft.Json.