Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress properties with null value on ASP.NET Web API

I've created an ASP.Net WEB API Project that will be used by a mobile application. I need the response json to omit null properties instead of return them as property: null.

How can I do this?

like image 988
Juliano Nunes Silva Oliveira Avatar asked Jan 23 '13 18:01

Juliano Nunes Silva Oliveira


People also ask

How do I pass a null parameter in Web API?

Simply add parameterName = null in your route parameter. Another option is add an overload. Have 2 function names receive different parameters. @kanika it's a precaution because there might be something yet to be setup in your controller and your controller is not accepting the parameters being sent.


2 Answers

In the WebApiConfig:

config.Formatters.JsonFormatter.SerializerSettings =                   new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}; 

Or, if you want more control, you can replace entire formatter:

var jsonformatter = new JsonMediaTypeFormatter {     SerializerSettings =     {         NullValueHandling = NullValueHandling.Ignore     } };  config.Formatters.RemoveAt(0); config.Formatters.Insert(0, jsonformatter); 
like image 54
Filip W Avatar answered Oct 16 '22 13:10

Filip W


I ended up with this piece of code in the startup.cs file using ASP.NET5 1.0.0-beta7

services.AddMvc().AddJsonOptions(options => {     options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); 
like image 45
sboulema Avatar answered Oct 16 '22 14:10

sboulema