这是一个完整的示例,它可以读取和写入多态对象的 JSON。
假设我们有以下类结构:
public class Base {}
public class SubClass1 : Base {
public int field1;
}
public class SubClass2 : Base {
public int field2;
}
我们可以使用自定义转换器,在序列化时在 JSON 中创建一个名为 type 的额外字段,并在反序列化时读取它。
public class PolymorphicJsonConverter : JsonConverter
{
public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
JObject item = JObject.Load(reader);
var type = item["type"].Value<string>();
if (type == "SubClass1") {
return item.ToObject<SubClass1>();
} else if (type == "SubClass2") {
return item.ToObject<SubClass2>();
} else {
return null;
}
}
public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) {
JObject o = JObject.FromObject(value);
if (value is SubClass1) {
o.AddFirst(new JProperty("type", new JValue("SubClass1")));
} else if (value is SubClass1) {
o.AddFirst(new JProperty("type", new JValue("SubClass2")));
}
o.WriteTo(writer);
}
public override bool CanConvert (Type objectType) {
return typeof(Base).IsAssignableFrom(objectType);
}
}
你可以像这样在容器类中使用这个转换器:
public class Container {
public List<Base> items;
public string Save() {
return JsonConvert.SerializeObject(items, new PolymorphicJsonConverter())
}
public void Load(string jsonText) {
items = JsonConvert.DeserializeObject<List<Base>>(jsonText, new PolymorphicJsonConverter());
}
}
或者,您可以使用 JSON.net 的内置类型提示,而不是滚动您自己的 JsonConverter,但它不是那么灵活,并且会创建非常不可移植的 JSON。
JsonConvert.SerializeObject(items, new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Auto
});