What Was I Thinking?

Follies & Foils of .NET Development
posts - 94 , comments - 350 , trackbacks - 0

How can I include my derived class type name in the serialized JSON?

Sometimes working with the js Serializer is easy, sometimes its not.   When I attempt to serialize an object that is derived from a base, the serializer decided whether or not to include the type name.

When its present, the type name is represented by a ___type attribute in the serialized json like this:

{"d":{"__type":"Commerce.Integration.Surfaces.OrderCreationRequest","RepId":0}}

The missing type name is a problem if I intend to ship the object back into a web method that needs to deserialize the object.   Without the Type name, serialization will fail and result in a ugly web exception.

The solution, which feels more like a work-around, is to explicitly tell the serializer to ALWAYS generate the type name for each derived type.  You make this declaration by adding a [GenerateScriptType())] attribute for each derived type to the top of the web page declaration.

 

For example, assuming I had 3 derivations of OrderCreationRequest; PersonalOrderCreationRequest, CompanyOrderCreationRequest, InternalOrderCreationRequestion, the code-behind for my web page would be decorated as follows:

    [GenerateScriptType(typeof(PersonalOrderCreationRequest))]
    [GenerateScriptType(typeof(CompanyOrderCreationRequest))]
    [GenerateScriptType(typeof(InternalOrderCreationRequest))]
    public partial class OrderMethods : Page
{
...
}
With the type names generated in the serialized JSON, the serializer can successfully deserialize instances of any of these types passed into a web method.
Hope this helps you as much as it did me. 

Print | posted on Thursday, June 30, 2011 8:35 PM | Filed Under [ Visual Studio ]

Feedback

Gravatar

# re: How can I include my derived class type name in the serialized JSON?

Hey, that's great! It helped me to fix some things in the webpage I'm programming right now.
1/12/2012 6:33 AM | Cleaners Clapham
Gravatar

# re: How can I include my derived class type name in the serialized JSON?

That's actually quite the neat bit of code. I'm just an amateur in programming, but I've been looking around, learning more and more about JSON. Thanks!
6/28/2012 6:09 AM | Carpet cleaners in Anerley
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: