【发布时间】:2013-01-06 14:15:25
【问题描述】:
我有一个带有基类子对象列表的对象。子对象需要自定义转换器。我无法让我的自定义转换器尊重 ItemTypeNameHandling 选项。
示例代码(新建一个 C# 控制台项目,添加 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"
}
]
}
我尝试在ToyConverter.WriteJson 方法中临时更改serializer.TypeNameHandling 的值,但它会影响不相关的属性。 (当然,我真正的转换器比这更复杂。这只是一个具有基本功能的示例。)
问题:如何让我的自定义 JsonConverter 尊重 ItemTypeNameHandling 属性的 JsonProperty 属性?
【问题讨论】:
-
您的目标是什么版本的 .NET?
-
我说的是你不需要TypeConvertor,来实现Toy子类型的序列化/反序列化。您也可以尝试仔细阅读和理解答案。我会删除我的答案。看来你已经什么都知道了,不需要任何帮助。
-
@I4V 我需要一个用于其他目的的自定义转换器,与“$type”无关。
标签: c# .net json serialization json.net