ignore null values globally in JSON output in aspnet method
Asked Answered
S

4

5

newbie question: how do i make my JSON output ignore null values? I don't want to necessarily set each individual property to ignore null (as in decorate each property with [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] ), and few different global methods I found and tried didn't work. I am using .Net 6 and Newtonsoft.Json

I have this method in my controller

[HttpPost]
public async Task<ResponseJson> Post([FromBody] RequestJson value)
{
    DataProcessor processor = new DataProcessor(value);
    return processor.GetResults();
}

This is what ResponseJson looks like (with some properties omitted for brevity).

public class ResponseJson
{
    [JsonProperty(PropertyName = "items")]
    public List<Item> Items { get; set; }
}   

public class Item
{
    [JsonProperty(PropertyName = "name")]
    public string name { get; set; }
    
    [JsonProperty(PropertyName = "colour")]
    public string colour { get; set; }
    
    [JsonProperty(PropertyName = "parameters")]
    public ItemParameters parameters { get; set; }
}

DataProcessor doesn't set the colour (null), or doesn't set ItemParameters at all for some of the Item. When looking at the response from calling this method, the JSON string looks like this:

{
    "items":
        [
            {
                "name":"abc",
                "colour": "blue",
                "parameters":{<a bunch of parameters>}
            },
            {
                "name":"def",
                "colour": null
                "parameters":null
            },
            {
                "name":"ghi",
                "colour": null,
                "parameters":null
            },
            {
                "name":"jkl",
                "colour": "red",
                "parameters":{<a bunch of parameters>}
            }
        ]
}   

I want the properties with null values to be ignored completely so that it looks like this:

{
    "items":
        [
            {
                "name":"abc",
                "colour": "blue",
                "parameters":{<a bunch of parameters>}
            },
            {
                "name":"def"
            },
            {
                "name":"ghi"
            },
            {
                "name":"jkl",
                "colour": "red",
                "parameters":{<a bunch of parameters>}
            }
        ]
}   
Silassilastic answered 31/3, 2022 at 21:40 Comment(3)
what is the advantage of ignoring the fields with nulls? During bind the missing fields become null.Anuria
shorter string?Silassilastic
you could introduce error. I would not parse the json string and remove unnecessary fields. to difficult to know the functionality of the end consumerAnuria
D
7

net core 6 web api, in program, add AddJsonOptions in your AddControllers

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddJsonOptions(options =>
{ 
   options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

in net core mvc

services.AddControllersWithViews().AddJsonOptions(options =>
{
 options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

in minimal API create service

builder.Services.Configure<JsonOptions>(options =>
{
    // Set this to true to ignore null or default values
    options.SerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
});

example complete using minimal API

using Microsoft.AspNetCore.Http.Json;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.Configure<JsonOptions>(options =>
{
    // Set this to true to ignore null or default values
    options.SerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}


app.MapGet("/GetWeatherForecast", () => new Person { FirstName = "Gérald"});
app.Run();

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

result without ignore null

{
  "FirstName": "Gérald",
  "LastName": null
}

result ignore null

{
  "firstName": "Gérald"
}
Dunkin answered 2/4, 2022 at 0:23 Comment(2)
What about same thing in minimal api? There is no controllers.Pickel
@Pickel I have updated the answer with an example using minimal apiDunkin
L
4

did you try this way?

services.AddControllersWithViews().AddNewtonsoftJson(o => {   o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;   });
Lamentable answered 31/3, 2022 at 22:4 Comment(0)
G
1

Add the below codes in the ConfigureServices method in Startup.cs file, and it will work

services.AddMvc()
.AddJsonOptions(options =>
{
    options.JsonSerializerOptions.IgnoreNullValues = true;
});

Seems the JsonSerializerOptions.IgnoreNullValues field is obsolete now, so try the new approach as stated below:

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    });
Galle answered 31/3, 2022 at 22:13 Comment(0)
D
1

For Minimal APIs running in DOTNET 7+ (probably 6 too) it is now as simple as the Minimal API Tutorial's section Configure JSON Serialization Options shows. Just use Builder.Services.ConfigureHttpJsonOptions() as per the excerpt bellow:

var builder = WebApplication.CreateBuilder(args);

builder.Services.ConfigureHttpJsonOptions(options => {
    options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    // set other desired options here...
    options.SerializerOptions.WriteIndented = true;
    options.SerializerOptions.IncludeFields = true;
});

var app = builder.Build();
Dode answered 16/7, 2023 at 15:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.