反序列化接口集合 [英] Deserializing a collection of interfaces
问题描述
我有以下可以完全序列化的类:
I have the following class which is perfectly serializable:
public class Form {
public IList<IControl> Controls { get; set; }
}
public class ControlA : IControl {}
public class ControlB : IControl {}
它序列化了而没有 $type
信息,但是我有一个自定义的JsonConverter
,它可以反序列化
It serializes without $type
information but I have a custom JsonConverter
which is able to deserialize all implementations of IControl
:
internal class MyJsonConverter : CustomCreationConverter<IControl> {}
在这样的情况下效果很好:
It works fine for a scenario like this:
[JsonConverter(typeof(MyJsonConverter ))]
public IControl MyControl {get;set;}
但是,我不能将相同的JsonConverterAttribute
应用于我的Form.Controls
属性:
However, I cannot apply the same JsonConverterAttribute
to my Form.Controls
property:
从JsonReader读取JObject时出错.当前的JsonReader项不是 对象:StartArray.路径控件",第5行,位置15."
"Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path 'Controls', line 5, position 15."
如何指示反序列化器将MyJsonConverter
用于内部 Form.Controls
集合?
How do I instruct the deserializer to use MyJsonConverter
for items inside Form.Controls
collection?
推荐答案
You can use [JsonProperty(ItemConverterType = typeof(MyJsonConverter))]
to apply the converter to the items in the collection:
public class Form
{
[JsonProperty(ItemConverterType = typeof(MyJsonConverter))]
public IList<IControl> Controls { get; set; }
}
这篇关于反序列化接口集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!