This project has moved and is read-only. For the latest updates, please go here.

deserializing heterogeneous collections

Nov 19, 2009 at 5:34 PM


I have a client-side collection that can contain classes which descend from a parent. For instance I might have a class called fruit, and two subclasses apple and orange. In the client I have an object List<fruit> and it is filled with apples and oranges.

On the server I have no problem serializing a list containing only fruit objects, but as soon as an apple or orange is added to the list the deserialization fails. I assume its because the converter is trying to set a property on the fruit object which is only defined in apple or orange. Right now all of my Json objects are stripped of their type information. Is there some way to make it so that I can include type info on the client-side in the Json representation of my fruit objects and have the server-side deserialization use that typeinfo to instantiate the proper fruit instance before trying to add the descendant properties?

If so how do I get Json.Net to look for this type info and create the correct object?

Thanks, Derek

Nov 19, 2009 at 8:54 PM

TypeNameHandling (found on JsonSerializerSettings) will allow you to include type information when serializing and deserializing.

Nov 19, 2009 at 9:51 PM

Ok the type info is now in the Json, however deserialization still fails as soon as I add something other than the base type to the collection.

Do I have to roll my own deserialization in order to handle this? The docs make it sound like Json.Net should take note of the type and instantiate the proper instance of the class before setting its properties.


Thanks, Derek


Nov 20, 2009 at 1:31 AM

It should work. If you post an example of what you're doing and the error message you are getting I can look at it.

Nov 20, 2009 at 2:32 AM

I got it working finally.

The problem was that I had used TypeNameHandling.All. I changed it to TypeNameHandling.Object and then the deserialization worked.


Thanks for your help, Derek