问题描述
我在 json 文件中有一个 List<ISomething>
,但我找不到简单的方法不使用 TypeNameHandling.All
反序列化它(我不想/不能使用,因为 JSON 文件是手写的).
I have a List<ISomething>
in a json file and I can't find an easy way todeserialize 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 membersof 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
是与这两个实现者的接口: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?
谢谢.
推荐答案
在您的班级中,您可以使用 JsonProperty
属性并使用 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(形状)
.然后 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 反序列化接口列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!