Newtonsoft.Json
Newtonsoft.Json copied to clipboard
[Feature request] omit JsonRequired in a nullable enable environment.
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.
@JamesNK I'm sorry, why is this not possible?
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 thank you What are STJs? Do you mean System.Text.Json?
yep