'ignore null values globally in JSON output in aspnet method

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>}
            }
        ]
}   


Solution 1:[1]

did you try this way?

services.AddControllersWithViews().AddNewtonsoftJson(o => {   o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;   });

Solution 2:[2]

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;
    });

Solution 3:[3]

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;
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ehsan Kenari
Solution 2
Solution 3 Daniel