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