我有一个带有基类子对象列表的对象。子对象需要自定义转换器。我不能让我的自定义转换器尊重ItemTypeNameHandling
选项。
示例代码(新建 C# Console 项目,添加 JSON.NET NuGet 包):
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace My {
class Program {
private static void Main () {
Console.WriteLine(JsonConvert.SerializeObject(
new Box { toys = { new Spintop(), new Ball() } },
Formatting.Indented));
Console.ReadKey();
}
}
[JsonObject] class Box
{
[JsonProperty (
ItemConverterType = typeof(ToyConverter),
ItemTypeNameHandling = TypeNameHandling.Auto)]
public List<Toy> toys = new List<Toy>();
}
[JsonObject] class Toy {}
[JsonObject] class Spintop : Toy {}
[JsonObject] class Ball : Toy {}
class ToyConverter : JsonConverter {
public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) {
serializer.Serialize(writer, value);
}
public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
return serializer.Deserialize(reader, objectType);
}
public override bool CanConvert (Type objectType) {
return typeof(Toy).IsAssignableFrom(objectType);
}
}
}
产生的输出:
{
"toys": [
{},
{}
]
}
必要的输出(如果我注释ItemConverterType = typeof(ToyConverter),
行会发生这种情况):
{
"toys": [
{
"$type": "My.Spintop, Serialization"
},
{
"$type": "My.Ball, Serialization"
}
]
}
我尝试过临时更改serializer.TypeNameHandling
inToyConverter.WriteJson
方法的值,但它会影响不相关的属性。(当然,我真正的转换器比这更复杂。这只是一个基本功能的例子。)
问题:如何使我的自定义JsonConverter
尊重ItemTypeNameHandling
属性的JsonProperty
属性?