I\'m writing an app that gets a Json
list of objects like this:
[
{
\"ObjectType\": \"apple\",
\"ObjectSize\": 35,
\"ObjectC
Some time ago I had the same problem.
You'll can use Json.NET, but if you don't have control over the json document (as in: 'it has been serialized by some other framework') you'll need to create a custom JsonConverter like this:
class MyItemConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(ItemToSell).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject obj = JObject.Load(reader);
string discriminator = (string)obj["ObjectType"];
ItemToSell item;
switch (discriminator)
{
case "apple":
item = new Apple();
break;
case "books":
item = new Books();
break;
case "melon":
item = new Melon();
break;
default:
throw new NotImplementedException();
}
serializer.Populate(obj.CreateReader(), item);
return item;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
}
Then you'll need to add it to the converters of the JsonSerializerSettings like so:
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
};
settings.Converters.Add(new MyItemConverter());
var items = JsonConvert.DeserializeObject>(response, settings);