将JSON反序列化为子类

时间:2013-07-06 06:43:03

标签: c# json.net

我有3个班级:

class Person {
    public bool IsFemale { get; set; }
}

class Female : Person {
    public string FemaleSpecificProperty { get; set; }
}

class Male: Person { 
    public string MaleSpecificProperty { get; set; }
}

如何根据Female属性的值将给定的JSON字符串反序列化为特定的实例(MalePerson.IsFemale)? (我不知道使用了哪种确切的类型,而且该属性是唯一的指示)

我看过使用CustomCreationConverter<T>,但无法弄清楚如何让它在这里工作。

1 个答案:

答案 0 :(得分:9)

这是您的人员班级的转换器。它会获得IsFemale字段值,并根据它创建FemaleMale人,该人员由序列化程序填充:

public class PersonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(Person).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType,
        object existingValue, JsonSerializer serializer)
    {
        JObject jObject = JObject.Load(reader);
        var isFemale = (bool)jObject["IsFemale"];
        Person target = isFemale ? (Person)new Female() : new Male();
        serializer.Populate(jObject.CreateReader(), target);
        return target;
    }

    public override void WriteJson(JsonWriter writer, object value, 
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

用法:

List<Person> people = new List<Person>
{
    new Male { IsFemale = false, MaleSpecificProperty = "Y" },
    new Male { IsFemale = false, MaleSpecificProperty = "Y" },
    new Female { IsFemale = true, FemaleSpecificProperty = "X" }
};

string json = JsonConvert.SerializeObject(people);
var result = 
     JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());

另请查看alex提出的问题:How to implement custom JsonConverter