Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ker1o opened this issue May 16, 2024 · 2 comments

Comments

@ker1o
Copy link

ker1o commented May 16, 2024

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
Copy link

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
Copy link

elgonzo commented May 24, 2024

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants