runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Fail null deserialization on non-nullable reference types

Open bwanner opened this issue 6 years ago • 48 comments

When deserializing "null" for a non-nullable value type System.Text.Json throws an Exception. However, for reference types this is not the case even if the project has the "Nullable" feature enabled.

Expectation: When nullable is enabled for the project deserializing null into a non-nullable type should fail for both value and reference types.

Question: This could be worked around by writing a custom Converter that honors nullable during deserialization. Are there plans to expose a setting to control the deserialization behavior for non-nullable reference types?

Repro: Deserializing DateTime as null fails (by design per this issue 40922). Deserializing List as null succeeds.

    class Program
    {
        public class MyDataObject
        {
            public DateTime Dt { get; set; }
            public List<int> MyNonNullableList { get; set; } = new List<int>();
        }

        static void Main(string[] args)
        {
            string input1 = "{\"Dt\":null, \"MyNonNullableList\":[42,32]}";
            string invalidInput = "{\"Dt\":\"0001-01-01T00:00:00\",\"MyNonNullableList\":null}";
            // Throws System.Text.Json.JsonException: 'The JSON value could not be converted to System.DateTime. Path: $.Dt | LineNumber: 0 | BytePositionInLine: 10.'
            // var validConverted = JsonSerializer.Deserialize<MyDataObject>(input1);

            // Does not throw Exception, but MyNonNullableList is null.
            var invalidConverted = JsonSerializer.Deserialize<MyDataObject>(invalidInput);
            Console.ReadKey();
        }
    }

bwanner avatar Jan 02 '20 22:01 bwanner

I fully agree. Also for consistency shouldn't the absence of a non-nullable also cause a fail?

(If we don't have something like this the whole advantage of nullable gets significantly negated as runtime types can deviate from compile-time checks. We're then back to manual fixes (run-time checks, custom converters or even attributes - all subject to human error and forgotten updates etc...).)

markm77 avatar Feb 14 '20 00:02 markm77

Expectation: When nullable is enabled for the project deserializing null into a non-nullable type should fail for both value and reference types.

I believe "nullable reference type" is a compile-time/static analysis feature. I don't think we can leverage it to affect runtime behavior of APIs like the JsonSerializer (or any other API in the framework). This is especially true because the nullable is opt-in, and the API runtime behavior should be the same regardless of whether the nullability analysis is enabled or not. Maybe I am mistaken, but I don't see how that's feasible.

The nullable annotation on the JsonSerializer.Deserialize method expresses this intent (return: MaybeNull), which is that it may return null even if the type is marked as non-nullable. That's because the JSON payload passed in could be the "null" literal and I don't think there is a runtime check we can leverage to detect that the user has a non-nullable reference type that they want to deserialize the unknown JSON string into. https://github.com/dotnet/runtime/blob/3a844ad951fda36fe3b570cc3af10738d898a7b3/src/libraries/System.Text.Json/ref/System.Text.Json.cs#L439-L440

What enabling the nullability will do is the compiler will warn you if you try to deserialize into a non-nullable reference type like your class. image

cc @safern, @stephentoub, @jcouv

Are there plans to expose a setting to control the deserialization behavior for non-nullable reference types?

Aside from implementing your own JsonConverter<T>, we could consider extending the behavior of [JsonIgnore] and the IgnoreNullValue option to apply at a property level, in which case, the null JSON value will be ignored and not override the initialized non-nullable reference type's value (in your case, list). We can consider this requirement as part of these two related feature: https://github.com/dotnet/runtime/issues/30687 / https://github.com/dotnet/runtime/issues/29861

cc @steveharter, @layomia

ahsonkhan avatar Feb 14 '20 04:02 ahsonkhan

Yes I also agree that the nullable annotation for Deserialize is correct as the payload may contain nulls no matter what the nullable reference type is when calling the deserialize method. Unfortunately even if IgnoreNullValue is honored to ignore null we don't have a way to express that via nullable reference types. We can't tell the compiler, if this property is true, the return value won't be null.

So that's why the compiler will warn you, this method my return null and you're using a non-nullable type. So what you got to do is declare your generic parameter and variable type as nullable.

MyDataObject? invalidConverted = JsonSerializer.Deserialize<MyDataObject?>(invalidInput);

safern avatar Feb 14 '20 06:02 safern

@ahsonkhan EF Core is actually doing this, when you have NRTs enabled, they'll make columns NULL / NOT NULL based on how your model class is annotated, see https://docs.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types

Suchiman avatar Feb 14 '20 10:02 Suchiman

So @ahsonkhan if I understand correctly you are suggesting a property attribute could be used to ensure NULL is ignored when de-serialising a non-nullable reference type. But don't we want a way to trigger an exception to be equivalent to the non-nullable value type case?

And if we have an attribute or way to trigger an exception with NULL would that not also solve the compiler warning issue mentioned by @safern in that the compiler flow analysis can see that an incoming NULL will lead to an exception and hence the conversion to non-nullable is safe?

I think it would be really great to have a solution that is compatible with the compile-time checker if possible. 😀

markm77 avatar Feb 14 '20 12:02 markm77

A couple of additional thoughts meant fully in the interests of making C# and .NET Core the best development environment possible.

Unfortunately even if IgnoreNullValue is honored to ignore null we don't have a way to express that via nullable reference types. We can't tell the compiler, if this property is true, the return value won't be null.

If the NRT complier flow analysis is not detecting things correctly, is it worth raising this with the compiler team? For example if the complier flow analysis is not smart about attributes shouldn't this be fixed?

So what you got to do is declare your generic parameter and variable type as nullable.

I realise it may take work from multiple teams but shouldn't we aim for a better solution than disabling the complier flow analysis (System.Diagnostics.CodeAnalysis.MaybeNull) and effectively not supporting NRT?

markm77 avatar Feb 15 '20 12:02 markm77

Any chance a fix for this is coming with .net 5?

Trolldemorted avatar Jul 02 '20 10:07 Trolldemorted

From @Eneuman in https://github.com/dotnet/runtime/issues/46431:

Using ReadFromJsonAsync in a nullable value type enabled .Net 5 ASP project has som strange behaviours.

For example: the following code return a MyClass? nullable object: var problemDetails = await response.Content.ReadFromJsonAsync<MyClass>();

This code returns a int (not nullable) (what happens if it is not a a numeric value in the response): var result = await response.Content.ReadFromJsonAsync<int>();

But this code returns a nullable string: var result = await response.Content.ReadFromJsonAsync<string>(); Shouldn't it return a none nullable string and throw if it is null?

layomia avatar Feb 03 '21 17:02 layomia

From @rathga in https://github.com/dotnet/runtime/issues/47178:

Summary

When deserializing Json to DTOs in MVC model binding, for non-nullable value type members null Json values are rejected, a nice error message is added to ModelState and a 400 error returned. However, for non-nullable reference types null values are let through which can then trip ArgumentNullExceptions in object constructors or property setters leading to a more cryptic 500 error rather than producing a 400 and a friendlier ModelState error.

An option could be added to (probably) JsonSerializerOptions so that it respects non-nullable reference types and throws a JsonException when encountering a null value, rather than binding the null value.

Motivation and goals

  • Current work around is to always use nullable reference types for all reference type members in DTOs, and defer null checks until after the constructor in validation or business logic. The DTO is unable to defend its not-null invariants itself, leading to pollution of the codebase with null checks elsewhere. Effectively this makes using nullable reference types not usable/useful for controller action DTOs.
  • An option could be added to (probably) JsonSerializerOptions so that it respects non-nullable reference types and throws a JsonException when encountering a null value, rather than binding the null value.

e.g. in Startup.cs

services.AddControllersWithViews()
    .AddJsonOptions(cfg => 
        cfg.JsonSerializerOptions.RespectNonNullableReferenceTypes = true
        );
  • This may be more aptly posted in the runtime repo as presumably the changes need to be in System.Text.Json, but as it is impacting me in my controllers I thought it would make sense to get feedback here first.

Examples

This small console app demonstrates the issue:

namespace JsonNullable
{
    static class Program
    {
        public record NullableInt(int? someNumber);
        public record NonNullableInt(int someNumber);

        public record NullableString(string? SomeString);
        public record NonNullableString
        {
            public string SomeString { get; }
            public NonNullableString(string someString) =>
                SomeString = someString ?? throw new ArgumentNullException(nameof(someString));
        }

        static void Main(string[] args)
        {
            var nullableInt = new NullableInt(null);
            var jsonInt = JsonSerializer.Serialize(nullableInt);
            var nonNullableInt = JsonSerializer.Deserialize<NonNullableInt>(jsonInt); 
            // ^^ throws Cannot get the value of a token type 'Null' as a number.
            // Gets handled gracefully by MVC model binding

            var nullableString = new NullableString(null);
            var jsonString = JsonSerializer.Serialize(nullableString); 
            var nonNullableString = JsonSerializer.Deserialize<NonNullableString>(jsonString);
            // ^^ throws ArgumentNullException from constructor
            // Causes 500 exception in MVC, forcing the null check to be removed from the DTO and performed after binding
        }
    }
}

layomia avatar Feb 03 '21 17:02 layomia

@layomia I have seen that this issue is also manifesting in https://github.com/dotnet/runtime/issues/52227. Do you have the required information about nullability in your code generators at hand that would allow you to support this with compile-time source generation?

Trolldemorted avatar Jun 21 '21 21:06 Trolldemorted

I believe "nullable reference type" is a compile-time/static analysis feature. I don't think we can leverage it to affect runtime behavior...

Would this help? "Expose top-level nullability information from reflection" (#29723) is slated for .NET 6 Preview 7.

JVimes avatar Jul 14 '21 20:07 JVimes

I might be missing something, but to me it may be more helpful to provide a way to define a fallback value for these types of fields. Imagine you create a model that you want to persist the serialized version of like so:

public class Dog
{
  public string Name { get; set; }
}

You serialize it and persist it, then go on to add another fields in an update:

public class Dog
{
  public string Name { get; set; }

  public string FavoriteFood { get; set; }
}

If you attempt to deserialize the JSON that was generated in a prior iteration of the class, it seems a little harsh to get exceptions and could break backwards compatibility. Instead, wouldn't it make sense to just be able to fallback the FavoriteFood field to string.Empty (or even better, a custom value). I realize I could create a default value like this:

public class Dog
{
  public string Name { get; set; }

  public string FavoriteFood { get; set; } = string.Empty;
}

But at that point, any Dog that is constructed has this default rather than those that are deserialized with the field missing.

If there is a feature that allows me to do this already, please let me know! I really appreciate it.

APIWT avatar Jul 15 '21 13:07 APIWT

...then go on to add another field... If you attempt to deserialize the JSON that was generated in a prior iteration of the class, it seems a little harsh to get exceptions...

@APIWT I don't think this ticket is about that. It's about JSON properties of value "JSON null" getting placed in .NET properties that are non-nullable.

JVimes avatar Jul 15 '21 15:07 JVimes

...then go on to add another field... If you attempt to deserialize the JSON that was generated in a prior iteration of the class, it seems a little harsh to get exceptions...

@APIWT I don't think this ticket is about that. It's about JSON properties of value "JSON null" getting placed in .NET properties that are non-nullable.

Totally, but I think these are very related problems. Right now, nullable reference types are pretty much incompatible with the serializers if they are going to give a false sense of security around runtime behavior. I just don't know if I agree with throwing an exception when deserializing something that should not be null and would much prefer a way to define a default behavior.

APIWT avatar Jul 15 '21 16:07 APIWT

Nullable annotations are not enforced by other APIs at runtime that I'm aware of. Source-gen and related design-time scenarios such as database-generation could use the annotations to help generate code to do that, however, which is one of the main scenarios for adding the feature Expose top-level nullability information from reflection.

Also I don't believe there is a guarantee that nullable annotations will always exist at runtime, since they are really there to support design-time \ compile-time scenarios. The annotations could be stripped out to save on assembly size, and for AOT scenarios that don't necessarily have corresponding IL and member metadata.

Recently "OnSerialize" interfaces were added so that POCOs can now validate before serialization and after deserialiation so null checks could be added there. E.g.:

    class Program
    {
        static void Main(string[] args)
        {
            // These all throw ArgumentNullException
            JsonSerializer.Deserialize<Person>("{}"); 
            JsonSerializer.Deserialize<Person>("{\"Name\":null}");
            JsonSerializer.Serialize(new Person());

            // This works:
            JsonSerializer.Deserialize<Person>("{\"Name\":\"Hello\"}");
        }
    }

    public class Person : IJsonOnDeserialized, IJsonOnSerializing
    {
        public string Name { get; set; }

        void IJsonOnDeserialized.OnDeserialized() => Validate();
        void IJsonOnSerializing.OnSerializing() => Validate();

        private void Validate()
        {
            if (Name is null)
            {
                throw new ArgumentNullException(nameof(Name));
            }
        }
    }

steveharter avatar Jul 15 '21 17:07 steveharter

@steveharter Bingo, this is exactly what I needed (IJsonOnDeserialized), thank you so much!!

APIWT avatar Jul 15 '21 17:07 APIWT

That's a lotta code when your model has dozens or hundreds of properties that shouldn't be null.

This ticket would be opt-in, no doubt. And I think it's still a great idea if it's implementable.

JVimes avatar Jul 16 '21 03:07 JVimes

I found a temporary solution as follows. I don't add the ThrowIfNull extension if it can be null.

public class User
{
   public User(string firstName, string? lastName)
   {
       FirstName = firstName.ThrowIfNull();
       LastName = lastName;
   }

   public string FirstName { get; set; }
   public string? LastName { get; set; }
}

public static class NullCheckParameter
{
    public static TKey ThrowIfNull<TKey>(this TKey value)
    {
        if (value == null)
            throw ArgumentNullException(typeof(TKey));

        return value;
    }
}

sinanbuyukbayrak avatar Jul 16 '21 05:07 sinanbuyukbayrak

I found a temporary solution as follows. I don't add the ThrowIfNull extension if it can be null.

Depends on your use case, but the whole idea for me here was to avoid getting as far as the constructor and tripping null checks. In MVC model binding this produces a 'cryptic' 500 error rather than a friendly 400 error with populated ModelState. See https://github.com/dotnet/runtime/issues/1256#issuecomment-772667048

@steveharter 's IJsonOnDeserialized, IJsonOnSerializing is interesting. Perhaps one solution is a source generator which automatically adds this to DTOs that you wish to have serialized that contain nullable reference types? Still seems cumbersome though compared to having System.Text.Json do it.

Even nullable attributes have been stripped or are absent, should this not be detectable at runtime? As such, setting cfg.JsonSerializerOptions.RespectNonNullableReferenceTypes = true could generate a warning or error to ensure you only use it with DTOs in assemblies where the attributes are present. And in fact, before you get there, you could just say to people that if you turn on this setting you better make sure you have nothing in your pipeline that is stripping out the attributes!

rathga avatar Jul 16 '21 08:07 rathga

ASP.net Core can detect properties that are non-nullable reference types at runtime. It even rejects the request if one of the non-nullable property is null. I however don't know if their code can detect non-nullable parameters as well.

For example, if I have this class:

   public class Dto
   {
      [JsonConstructor]
      public Dto(string value, string? optionalValue)
      {
         Value = value;
         OptionalValue = optionalValue;
      }

      public string Value { get; }

      public string? OptionalValue { get; }
   }

and the JSON payload is empty {}

ASP.net returns:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-5b5a8fd1b496464796a2992b194b5482-fb67217921735b4f-00",
    "errors": {
        "Value": [
            "The Value field is required."
        ]
    }
}

Note that only Value is required because OptionalValue is a nullable reference type.

The ASP.net code that detects non-nullable reference types is in DataAnnotationsMetadataProvider (link to the code) and it can be toggled on/off via MvcOptions.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes

lostincomputer avatar Oct 17 '21 05:10 lostincomputer