反序列化接口集合 [英] Deserializing a collection of interfaces

查看:195
本文介绍了反序列化接口集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下可以完全序列化的类:

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,它可以反序列化>的 all 实现:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆