JamesNK / Newtonsoft.Json

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

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

Open aijkl opened 1 year ago

aijkl commented 1 year ago

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 commented 1 year ago

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

sungam3r commented 1 year ago

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.

aijkl commented 1 year ago

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

sungam3r commented 1 year ago

yep