Using ReadAsDataContract to deserialize a complex type

Topics: Web Api
Feb 6, 2011 at 2:30 AM

I have a complex class structure that can be returned from my get call.

The call is defined as public FanBase Get(int id) which is mapped to a url of /FanObject/id. 

There are 8 classes that are derived from FanBase and any of them can be returned on the call.

How can I use ReadAsDataContract to deserialize the correct object?  The object being returned is correctly represented in the XML.  All the classes are in a schema/data contract library that both the client and the server have access to.

I've tried using ReadAsDataContract setting it to the base type and provided an array of all the other possible types. 

It still throws a serialization error about not being able to resovle the correct type.

Any thoughts/suggestions?



Feb 7, 2011 at 1:28 PM

Using inheritance and polymorphism in data contracts / service operations can be cumbersome.  Since you're attempting to return a base type or generic, the datacontractresolver doesn't know the underlying types to serialize.  I'm assuming you have set KnownTypeAttributes on your contracts?

Juval Lowy just wrote a good article on data contract resolvers and generic resolver in this month's MSDN magazine. See the article here.

Hope this helps.

Feb 7, 2011 at 2:20 PM

dgdev, thank you for your thoughts.

I will go back and re-read the article.  When I first read it on Friday, it didn't seem to be on point.

I do know that if I expose the same classes via wsHttp the client can successfully determine that object type and instantiate the correct object.  How does WCF get this to work with DataContractSerializer?