Sinaesthetic Sinaesthetic - 1 month ago 46
C# Question

How do I deserialize a derived class with json.net

I'm currently getting back the following json from a service that I do not own:

{
"auc" : 320658953,
"item" : 31294,
"owner" : "Amacid",
"ownerRealm" : "EarthenRing",
"bid" : 289493,
"buyout" : 371150,
"quantity" : 1,
"timeLeft" : "LONG",
"rand" : 0,
"seed" : 0,
"context" : 0
}, {
"auc" : 321175921,
"item" : 82800,
"owner" : "Drakonys",
"ownerRealm" : "EarthenRing",
"bid" : 7000384,
"buyout" : 7507980,
"quantity" : 1,
"timeLeft" : "VERY_LONG",
"rand" : 0,
"seed" : 161297536,
"context" : 0,
"petSpeciesId" : 293,
"petBreedId" : 9,
"petLevel" : 1,
"petQualityId" : 3
},


And I'm trying to deserialize it into proper CLR objects. It's obvious that these object hold a an object hierarchy on the server side; something like
Item
and
PetItem : Item
where
PetItem
has the extra 4 properties at the end there.

How do I handle this? I'm using Json.net to deserialize most of the other results from other services that are more consistent, but I'm looking for a strategy to handle situations like this. I've seen some solutions on how to have Json.net deserialize everything into an implied base class, but I'm not sure how to handle this upcasting type scenario

Answer Source

Here is yours example: http://dotnetbyexample.blogspot.ru/2012/02/json-deserialization-with-jsonnet-class.html?m=1

You just have to use overloaded method

JsonConvert.DeserializeObject<List<Item>>
  (r.EventArgs.Result, params Newtonsoft.Json.JsonConverter[] converters)

And write your converters