.NET Core: Remove null fields from API JSON response

后端 未结 6 1434
无人共我
无人共我 2020-12-08 03:58

On a global level in .NET Core 1.0 (all API responses), how can I configure Startup.cs so that null fields are removed/ignored in JSON responses?

Using Newtonsoft.Js

相关标签:
6条回答
  • 2020-12-08 04:10

    I found that for dotnet core 3 this solves it -

    services.AddControllers().AddJsonOptions(options => {
         options.JsonSerializerOptions.IgnoreNullValues = true;
    });
    
    0 讨论(0)
  • 2020-12-08 04:12

    This can also be done per controller in case you don't want to modify the global behavior:

    public IActionResult GetSomething()
    {
       var myObject = GetMyObject();
       return new JsonResult(myObject, new JsonSerializerSettings() 
       { 
           NullValueHandling = NullValueHandling.Ignore 
       });
    };
    
    0 讨论(0)
  • 2020-12-08 04:23

    The following works for .NET Core 3.0, in Startup.cs > ConfigureServices():

    services.AddMvc()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.IgnoreNullValues = true;
        });
    
    0 讨论(0)
  • 2020-12-08 04:25

    In Asp.Net Core you can also do it in the action method, by returning

    return new JsonResult(result, new JsonSerializerOptions
    {
       IgnoreNullValues = true,
    });
    
    0 讨论(0)
  • 2020-12-08 04:33

    The code below work for me in .Net core 2.2

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
    0 讨论(0)
  • 2020-12-08 04:34

    [.NET Core 1.0]

    In Startup.cs, you can attach JsonOptions to the service collection and set various configurations, including removing null values, there:

    public void ConfigureServices(IServiceCollection services)
    {
         services.AddMvc()
                 .AddJsonOptions(options => {
                    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
         });
    }
    

    [.NET Core 3.1]

    Instead of:

    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    

    Use:

    options.JsonSerializerOptions.IgnoreNullValues = true;
    
    0 讨论(0)
提交回复
热议问题