将JSON反序列化为子类



我有三个类:

class Person {
    public bool IsFemale { get; set; }
}
class Female : Person {
    public string FemaleSpecificProperty { get; set; }
}
class Male: Person { 
    public string MaleSpecificProperty { get; set; }
}

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

我考虑过使用CustomCreationConverter<T>,但不知道如何在这里工作。

这是您的person类的转换器。它获取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提出的问题:如何实现自定义JsonConverter

相关内容

  • 没有找到相关文章

最新更新