我有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字符串反序列化为特定的实例(Male
或Person.IsFemale
)? (我不知道使用了哪种确切的类型,而且该属性是唯一的指示)
我看过使用CustomCreationConverter<T>
,但无法弄清楚如何让它在这里工作。
答案 0 :(得分:9)
这是您的人员班级的转换器。它会获得IsFemale
字段值,并根据它创建Female
或Male
人,该人员由序列化程序填充:
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