Monday, March 26, 2012

Deserializing derived objects

Hello!

Maybe my question is rather stupid, but I'm just a newbie...

I have some classes derived from class DataObject, for example Account:

public

classAccount :DataObject {...}

and a [ScriptService()] - marked .asmx service with method

[

WebMethod( EnableSession =true )]publicDataObject AddObject(DataObject dataObject )

which passes this dataObject to another .svc service which writes it to database...

I call AddObject method throughSys.Net.WebServiceProxy.invoke(...), passing JavaScript object corresponding to Account class (I mean it has the same fields). If I set the parameter type in AddObject method to Account - everything works fine, it serializes and deserializes correct and passes further as an Account object. But if I try to set parameter type to DataObject - it looks like deserializer cuts all fields that are not declared in DataObject class and doesn't recognize derived object. The dataObject object in this method is pure DataObject, not Account.

I want to handle objects this way because actually I have now something about 10 classes and 10 such methods, and their number may increase. Writing all methods like AddAccount, AddUser, AddQuote and so on looks unhandy for me.

Is it possible for default JavaScriptSerializer to recognize derived objects? Or if I have to redefine it - how could I do that?

Thank you!

I faced a similar problem. The issue at hand is that the module that does the serialization/deserialization will look to the return types and parameters as cues for what it should serialize to / deserialize to , and it doesn't look deeper than that. I ended up doing a fairly hacky work-around to get the code in on time, but at some point I'm probably going to try and figure out a good solution.

A couple thoughts I had, neither of which are tried out. First, I'm aware that you can generate javascript types for nested types of the web service class (seehttp://ajax.asp.net/docs/mref/T_System_Web_Script_Services_GenerateScriptTypeAttribute.aspx) so that's an option, I suppose. Seems like not the best solution in our case, though, as what we're working with aren't logically nested types of the web service. I also considered writing a serializer module that can take the first param as a type argument so that, at the least, you could specify which concrete type you're sending upstream.instead of letting the module map only to the types in the webmethod params.


For XML Serialization (as used in classic 2.0 asmx web services) there is an attribute called XmlInclude which allows you to specify specializations of the actual return type. omly the ones you list with XmlInclude will be taken into account by the XmlSerializer.

I know the script service infrastructure hooks into the classic asmx stuff, but I have no idea if it looks at XmlInclude-s to. You might give it a try ...

-- Henkk

No comments:

Post a Comment