What Was I Thinking?

Follies & Foils of .NET Development
posts - 95 , comments - 352 , trackbacks - 0

Thursday, June 30, 2011

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:


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:

    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. 

Posted On Thursday, June 30, 2011 8:35 PM | Comments (2) | Filed Under [ Visual Studio ]

Powered by: