How can I include my derived class type name in the serialized JSON?
Posted
by ChrisD
on Geeks with Blogs
See other posts from Geeks with Blogs
or by ChrisD
Published on Fri, 01 Jul 2011 01:35:34 GMT
Indexed on
2011/07/01
8:23 UTC
Read the original article
Hit count: 251
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.
© Geeks with Blogs or respective owner