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>}
}
]
}
3
Answers
did you try this way?
Add the below codes in the
ConfigureServices
method inStartup.cs
file, and it will workSeems the
JsonSerializerOptions.IgnoreNullValues
field is obsolete now, so try the new approach as stated below:net core 6 web api, in program, add
AddJsonOptions
in yourAddControllers
in net core mvc
in minimal API create service
example complete using minimal API
result without ignore null
result ignore null