Search code examples
asp.net-web-apiodataasp.net-web-api2

serialize null navigation property


I have simple class:

public class Person
{
   public string Name {get; set;}
   public Address Address {get; set;} // can be null
}

When I query Person I want webapi return me empty Address property. I tryed the following:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings()
            {
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Include,

            };

but, nothing chaged, it's just not exist in result.


Solution

  • You don't need to configure the formatter, just add $expand query option:

    GET ~/Person?$expand=Address
    

    I tried, it works. and I'm using WebApi OData for OData v4.

    {
      "@odata.context":"http://jinfutan13:9123/$metadata#Albums/$entity",
      "ID":5,"Name":"Name 5",
      "Singer":null
    }
    

    Where Singer is also a navigation property.