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?


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.


If you write your class following:

public class MyClass
{
    // properties here

    public string IType
    {
        get
        {
            return this.GetType().Name;
        }

        set {  }
    }
}

Maybe, it will help you

链接地址: http://www.djcxy.com/p/64228.html

上一篇: Android画布会改变一些像素的颜色

下一篇: 继承和ASP.NET Web API的JSON格式化程序