Gillardo
Gillardo

Reputation: 9828

Set NullValueHandling at a controller level

For the moment part, i would like to exclude null values from my api response, so in my startup.cs file, i have this.

services.AddMvc()
    .AddJsonOptions(options =>
    {
        // Setup json serializer
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
    });

But is it possible to state that on 1 or more controllers, i actually want to include NULL values??

Upvotes: 11

Views: 2386

Answers (2)

Oleg
Oleg

Reputation: 221997

You can get JsonOutputFormatter from the BindingContext.OutputFormatters inside of the code of your controller. It allows you dynamically change the SerializerSettings.

Try to include using Newtonsoft.Json; in the controller code and to do the following inside of your controller action:

var f = BindingContext.OutputFormatters.FirstOrDefault(
            formatter => formatter.GetType() ==
                         typeof (Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter))
        as Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter;
if (f != null) {
    //f.SerializerSettings.Formatting = Formatting.Indented;
    f.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
}

I included Formatting = Formatting.Indented just for my tests only, because one see the results immediately. You don't need it of cause.

UPDATED: I created the demo project using MVC Web Application with no Authentication. Then I added in HomeController the following metod

public object TestMethod()
{
    var testResult = new {
                         name = "Test",
                         value = 123,
                         nullableProperty = (string) null
                     };

    return testResult;
}

and changed the Launch URL of the project to Home/TestMethod and started the demo. I could see

{"name":"Test","value":123,"nullableProperty":null}

You don't need to add any additional using statements to use the code which I posted initially (one need just have the standard using Microsoft.AspNet.Mvc; and using System.Linq;), but the code could be more readable if you would have using Microsoft.AspNet.Mvc.Formatters; and using Newtonsoft.Json;. I added the using statements for Microsoft.AspNet.Mvc.Formatters and Newtonsoft.Json and modified the code to the following

public object TestMethod()
{
    var testResult = new {
                         name = "Test",
                         value = 123,
                         nullableProperty = (string) null
                     };

    var f = BindingContext.OutputFormatters.FirstOrDefault(
                formatter => formatter.GetType() == typeof (JsonOutputFormatter)) as JsonOutputFormatter;
    if (f != null) {
        f.SerializerSettings.Formatting = Formatting.Indented;
        f.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    }
    return testResult;
}

The output results looks now as following

{
  "name": "Test",
  "value": 123
}

The standard code use "Newtonsoft.Json" in version 6.0.6. We can add "Newtonsoft.Json": "8.0.2" in dependencies to use the latest version of Newtonsoft.Json. See the problem with resolving of indirect dependencies which I reported in the issue and which is still opened.

You can download the test project from here.

Upvotes: -1

csharpfolk
csharpfolk

Reputation: 4290

One option is to create custom Json result type, as described in this question: Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible?. Then you can have bool var on base controller and use it do disable null's when using custom Json result or even pass option directly:

return Json(data, ignoreNulls: true); 

Upvotes: 5

Related Questions