Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and the JSON formatter of ASP.NET Web API

Imagine a simple controller action IEnumerable<BaseType> Get(). It returns an enumeration of different types all deriving from BaseType.

When the client requests XML, the result is something like this:

<ArrayOfBaseType>
    <BaseType i:type="DerivedType1"><A>value</A></BaseType>
    <BaseType i:type="DerivedType2"><B>value</B></BaseType>
    <BaseType i:type="DerivedType3"><C>value</C></BaseType>
</ArrayOfBaseType>

As you can see, the type of the derived class is transmitted in the i:type attribute.

If the client requests JSON however, this information is missing:

[
  {"A":"value"},
  {"B":"value"},
  {"C":"value"}
]

How to fix this?

like image 664
Daniel Hilgarth Avatar asked Sep 29 '12 09:09

Daniel Hilgarth


1 Answers

The following change is necessary:

In the WebApiConfig.cs the following line needs to be added:

config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = 
    TypeNameHandling.Auto;

This will automatically result in a new property $type when needed.

like image 96
Daniel Hilgarth Avatar answered Sep 20 '22 11:09

Daniel Hilgarth