Home > Back-end >  ignore null values globally in JSON output in aspnet method
ignore null values globally in JSON output in aspnet method

Time:04-01

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

CodePudding user response:

did you try this way?

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

CodePudding user response:

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