Search code examples
serializationjson.net.net-6.0

.Net 6 is requiring all non-nullable fields when I try to deserialize JSON


I'm converting an app from .Net standard to .Net 6, but my controllers are throwing errors if I don't pass in all non-nullable fields. e.g.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string CustomerType { get; set; }
}

When I try to pass that object to an action without one of the fields, it throws an error like "The FirstName field is required." How can I get around that? I'm using NewtonSoft via the startup file like this:

builder.Services.AddControllers()
    .AddNewtonsoftJson(options => 
    { 
        options.UseMemberCasing();
    });

builder.Services.AddControllersWithViews()
    .AddNewtonsoftJson(options =>
    {
        options.UseMemberCasing();
    });

Solution

  • the easiest way is to open a project configuratuon file (just click on project name in a VS solution explorer) and remove option nullable

    <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <Nullable>disable</Nullable>   <!-- change from enable or remove --> 
        <ImplicitUsings>enable</ImplicitUsings>
      </PropertyGroup>
    

    or if you want to dissable nullabel check only in the controllers actions, you can try another option

    builder.Services.AddControllers(
        options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);