Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI not returning JSON for INT when value is zero

I have this class, as a cut down version:

public class SportTableRow
{
    public Int32 Won { get; set; }
    public Int32 Lost { get; set; }
    public Int32 Drawn { get; set; }
    public Int32 For { get; set; }
}

When I make a call to the Data via the WebAPI, it looks like this (again cut down)...

public List<SportTableRow> Get()
        {
            var options = ....
            var sport = ....
            var locationCode = ...

            return SportManager.GetOverallTable(sport, options, 
                      locationCode).TableRows;
        }

When I inspect the returned data in debugger, you can see the properties in the list...

enter image description here

But, when I call via fiddler, you can see that a few properties are missing...

enter image description here

...and it seems to be any Int's that are 0, and bool's which are false etc.

Do I need to set anything on the actual class, or something in the JSON serializer?

like image 590
Christian Phillips Avatar asked Nov 02 '13 15:11

Christian Phillips


1 Answers

The JSON serializer JSON.NET is set by default to exclude properties that are set to default values. For Example, boolean=false, int=0, int?=null, object=null, etc. will be excluded from the resulting JSON. The intention is to minimize bandwidth.

You can change this behavior by changing the settings:

    System.Web.Http
              .GlobalConfiguration.Configuration
              .Formatters
              .JsonFormatter
              .SerializerSettings
              .DefaultValueHandling 
                             = Newtonsoft.Json.DefaultValueHandling.Include;

Best add this line in the Global.asax file. But note: This will just add bandwidth with no real benefit, especially if you control the client side too

like image 146
user2674389 Avatar answered Sep 28 '22 02:09

user2674389