I\'m writing an app that gets a Json
list of objects like this:
[
{
\"ObjectType\": \"apple\",
\"ObjectSize\": 35,
\"ObjectC
You can use a CustomCreationConverter. This lets you hook into the deserialization process.
public abstract class Base
{
public string Type { get; set; }
}
class Foo : Base
{
public string FooProperty { get; set; }
}
class Bar : Base
{
public string BarProperty { get; set; }
}
class CustomSerializableConverter : CustomCreationConverter
{
public override Base Create(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
var type = (string)jObject.Property("Type");
Base target;
switch (type)
{
case "Foo":
target = new Foo();
break;
case "Bar":
target = new Bar();
break;
default:
throw new InvalidOperationException();
}
serializer.Populate(jObject.CreateReader(), target);
return target;
}
}
class Program
{
static void Main(string[] args)
{
var json = "[{Type:\"Foo\",FooProperty:\"A\"},{Type:\"Bar\",BarProperty:\"B\"}]";
List bases = JsonConvert.DeserializeObject>(json, new CustomSerializableConverter());
}
}