使用自定义JsonConverter反序列化接口列表? [英] Deserializing a list of interfaces with a custom JsonConverter?
问题描述
我在json文件中有一个 List< ISomething>
,但我找不到一种简单的方法来反序列化它,而无需使用 TypeNameHandling.All
(由于JSON文件是手写的,所以我不希望/不能使用它.)
I have a List<ISomething>
in a json file and I can't find an easy way to
deserialize it without using TypeNameHandling.All
(which I don't want / can't use because the JSON files are hand-written).
有没有一种方法可以将属性 [JsonConverter(typeof(MyConverter))]
应用于成员而不是列表中的列表?
Is there a way to apply the attribute [JsonConverter(typeof(MyConverter))]
to members
of the list instead to the list?
{
"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
.
In this case, Shapes
is a List<IShape>
where IShape
is an interface with these two implementors:
ShapeRect
and ShapeDxf
.
我已经创建了一个JsonConverter子类,该子类将该项目作为JObject加载,然后根据给定的属性 Path
是否存在来检查要加载的实际类:
I've already created a JsonConverter subclass which loads the item as a JObject and then checks which real class to load given the presence or not of the property Path
:
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应用于列表?
How can I apply this JsonConverter to a list?
谢谢.
推荐答案
在您的课程中,您可以使用 ItemConverterType
参数:
In your class, you can mark your list with a JsonProperty
attribute and specify your converter with the ItemConverterType
parameter:
class Foo
{
public Size Size { get; set; }
[JsonProperty(ItemConverterType = typeof(MyConverter))]
public List<IShape> Shapes { get; set; }
}
或者,您可以将转换器的实例传递给 JsonConvert.DeserializeObject
,假设您已经实现了 CanConvert
,以便当 objectType == typeof时它返回true.(IShape)
.然后,Json.Net会将转换器应用到列表中的项目.
Alternatively, you can pass an instance of your converter to JsonConvert.DeserializeObject
, assuming you have implemented CanConvert
such that it returns true when objectType == typeof(IShape)
. Json.Net will then apply the converter to the items of the list.
这篇关于使用自定义JsonConverter反序列化接口列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!