Deny null-value properties in ASP.NET Web API

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

How can i do this?

+67
asp.net-web-api
Jan 23 '13 at 18:23
source share
4 answers

In WebApiConfig :

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

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

  var jsonformatter = new JsonMediaTypeFormatter { SerializerSettings = { NullValueHandling = NullValueHandling.Ignore } }; config.Formatters.RemoveAt(0); config.Formatters.Insert(0, jsonformatter); 
+102
Jan 23 '13 at 18:25
source share

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; }); 
+16
Oct 16 '15 at 9:44
source share

If you use vnext, in vnext web api projects, add this code to the startup.cs file.

  public void ConfigureServices(IServiceCollection services) { services.AddMvc().Configure<MvcOptions>(options => { int position = options.OutputFormatters.FindIndex(f => f.Instance is JsonOutputFormatter); var settings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }; var formatter = new JsonOutputFormatter(); formatter.SerializerSettings = settings; options.OutputFormatters.Insert(position, formatter); }); } 
+3
Apr 22 '15 at 13:01
source share

I know this topic has been around for about two years, but if you go back to the JSON.NET documentation, it has detailed information on how to solve the problem of reducing the serialized JSON size for different scenarios, such as ignoring all null, ignoring all the values by default, ignoring null or default value only for certain properties, etc .:

http://www.newtonsoft.com/json/help/html/reducingserializedjsonsize.htm

0
Apr 29 '16 at 21:10
source share



All Articles