使用自定义JsonConverter反序列化接口列表?
问题描述:
我有一个List<ISomething>
在json文件中,我无法找到一个简单的方法来 反序列化它,而不使用TypeNameHandling.All
(我不想/不能使用,因为JSON文件是手写的)。使用自定义JsonConverter反序列化接口列表?
有没有办法将属性[JsonConverter(typeof(MyConverter))]
应用到列表的成员 而不是列表?
{
"Size": { "Width": 100, "Height": 50 },
"Shapes": [
{ "Width": 10, "Height": 10 },
{ "Path": "foo.bar" },
{ "Width": 5, "Height": 2.5 },
{ "Width": 4, "Height": 3 },
]
}
在这种情况下,Shapes
是List<IShape>
其中IShape
是与这两个实施者的接口: ShapeRect
和ShapeDxf
。
我已经创建了加载项作为真正的类来加载给出的存在或不存在财产Path
一个JObject,然后检查一个JsonConverter子类:
var jsonObject = JObject.Load(reader);
bool isCustom = jsonObject
.Properties()
.Any(x => x.Name == "Path");
IShape sh;
if(isCustom)
{
sh = new ShapeDxf();
}
else
{
sh = new ShapeRect();
}
serializer.Populate(jsonObject.CreateReader(), sh);
return sh;
如何申请这个JsonConverter列表?
谢谢。
答
在你的类,你可以用JsonProperty
属性标记您的列表,并与ItemConverterType
参数指定转换器:
class Foo
{
public Size Size { get; set; }
[JsonProperty(ItemConverterType = typeof(MyConverter))]
public List<IShape> Shapes { get; set; }
}
或者,你可以通过你的转换器的一个实例JsonConvert.DeserializeObject
,假设你已经实现CanConvert
,使其在objectType == typeof(IShape)
时返回true。 Json.Net然后将转换器应用到列表中的项目。
['JsonPropertyAttribute.ItemConverterType'](http://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonPropertyAttribute_ItemConverterType.htm) – kiziu
@kiziu非常感谢!我无法在Google上找到... :( – TesX