8

我有 3 节课:

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

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

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

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

我看着招聘,CustomCreationConverter<T>但不知道如何让它在这里工作。

4

1 回答 1

12

这是您的人员类的转换器。它获取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

于 2013-07-06T08:21:19.927 回答