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

[Feature request] omit JsonRequired in a nullable enable environment.

Open aijkl opened this issue 1 year ago • 4 comments

Source/destination types

#nullable enable
using Newtonsoft.Json;
using System;

public class Model 
{
	public Model(string name)
	{
		Name = name;
	}
	
	public string Name { set; get; }
}

public class Program
{
	public static void Main()
	{			
		var json = "{}";
		var model = JsonConvert.DeserializeObject<Model>(json); // need error
		Console.WriteLine(model.Name);
	}	
}

Source/destination JSON

{}

Expected behavior

Even if JsonRequriedAttibute is not set, in #nullable enabled environment, I want to throw "Newtonsoft.Json.JsonSerializationException: Required property 'Name' not found" Is.

I don't think this can be the default setting as it is a disruptive change But you can enable it by setting it in JsonConvert.DefaultSettings

Actual behavior

In actual operation, even with #nullable enable, if JsonRequired is not set, a JonSerializationException will not be thrown So Model.Name will be null.

Steps to reproduce

#nullable enable
using Newtonsoft.Json;
using System;

public class Model 
{
	public Model(string name)
	{
		Name = name;
	}
	
	public string Name { set; get; }
}

public class Program
{
	public static void Main()
	{			
		var json = "{}";
		var model = JsonConvert.DeserializeObject<Model>(json); // No errors
		Console.WriteLine(model.Name == null); // True
	}	
}

Thanks for the great library.

aijkl avatar Apr 02 '23 10:04 aijkl

@JamesNK I'm sorry, why is this not possible?

aijkl avatar May 07 '23 11:05 aijkl

There have been no comments yet that it is impossible. I think implementing such features like this one brings a low of additional work manipulating with NRT annotations and simply is not in the focus of project. Honestly NSJ receives only bugfixes for a long time and I'm sure that "semi-official" position is to migrate to STJ.

sungam3r avatar May 08 '23 06:05 sungam3r

@sungam3r thank you What are STJs? Do you mean System.Text.Json?

aijkl avatar May 08 '23 06:05 aijkl

yep

sungam3r avatar May 08 '23 06:05 sungam3r