Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't make MVC4 WebApi include null fields in JSON

I'm trying to serialize objects as JSON with MVC4 WebAPI (RTM - just installed VS2012 RTM today but was having this problem yesterday in the RC) and I'd like for all nulls to be rendered in the JSON output. Like this:

[{"Id": 1, "PropertyThatMightBeNull": null},{"Id":2, "PropertyThatMightBeNull": null}]

But what Im getting is

[{"Id":1},{"Id":2}]

I've found this Q/A WebApi doesnt serialize null fields but the answer either doesn't work for me or I'm failing to grasp where to put the answer.

Here's what I've tried:

  1. In Global.asax.cs's Application_Start, I added:

    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;
    json.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
    

    This doesn't (seem to) error and seems to actually execute based on looking at the next thing I tried.

  2. In a controller method (in a subclass of ApiController), added:

    base.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;
    base.Configuration.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
    

    I say #1 executed because both values in #2 were already set before those lines ran as I stepped through.

  3. In a desperation move (because I REALLY don't want to decorate every property of every object) I tried adding this attrib to a property that was null and absent:

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Include,
        NullValueHandling = NullValueHandling.Include)]
    

All three produce the same JSON with null properties omitted.

Additional notes:

  • Running locally in IIS (tried built in too), Windows 7, VS2012 RTM.
  • Controller methods return List -- tried IEnumerable too
  • The objects I'm trying to serialize are pocos.
like image 823
AndrewFreese Avatar asked Aug 17 '12 02:08

AndrewFreese


Video Answer


1 Answers

This won't work:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;

But this does:

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() 
{ 
NullValueHandling = Newtonsoft.Json.NullValueHandling.Include
};
like image 82
Filip W Avatar answered Sep 23 '22 07:09

Filip W