7

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?

1
  • 3
    @downvoter: Without an explanation, your downvote is worth nothing as I can't improve the question without knowing what is unclear. Commented Sep 29, 2012 at 11:50

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Not really. In my eyes that's a hack.
I'm not sure with json exists another way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.