user1843640 user1843640 - 2 months ago 12
C# Question

Web API converted to Azure Mobile Service not serializing all properties

I have a working Web API that i am converting to a .Net Azure Mobile Service. The API returns a complex model - objects with properties - some of which are collections of other objects. This works as expected with plain Web API but with Azure Mobile Services I have an issue where one of my models does not have all it's properties serialized.

When i set a break point on the return statement in the controller, I see that all the properties and their values are present. This leads me to believe that the issue is with serialization (JSON).

return Request.CreateResponse(HttpStatusCode.OK, myModel);


Examples of properties that are being serialized:

public Guid Id { get; set; }
public IEntityDto ModelDto { get; set; } //this is an object with many properties all of which serialize


Examples of properties that are NOT being serialized:

public ItemStatus Status { get; set; } //this is an enum
public string Message { get; set; }
public string TestProp { get; set; } //this is a simple string property I added to help debug


How can I go about further debugging this so that i can see why these properties are being excluded?

Note: At the moment I am still running this locally not off Azure. This is with Visual Studio 2013 Update 2 RTM.

UPDATE: Upon closer inspection it appears that the properties not being serialized are properties that are either enums or have a value of null.

Answer

As @carlosfigueira mentioned in a comment to the original question, the default behavior of the JSON serializer is to exclude properties with null and default values. To address this I changed the following settings:

  httpConfig.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
  httpConfig.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;

...where httpConfig is of type HttpConfiguration. You can make these changes on app start - in a config file like WebApiConfig.cs or directly in Global.asax.cs.