【问题标题】:Serializing a list of interface objects序列化接口对象列表
【发布时间】:2016-06-28 23:09:39
【问题描述】:

使用 Json.net,我想反序列化一个包含接口对象的篮子。 这……

{
"Owner": "John",
"Fruit": [ <an apple object>, <a pear>, etc... ]
}

...应该进入这个...

class Basket
{
string Owner;
List<iFruit> Fruit; //contains instances of Apple, Pear,...
}

接口无法实例化,因此需要转换为具体对象。我找到了使用 JsonConverter 创建具体 Apple 和 Pear 实例的示例。但是列表总是直接用这样的一行来创建的:

List<iFruit> fruit = JsonConvert.DeserializeObject<List<iFruit>>(json, new FruitConverter());

如何反序列化整个篮子,其中 JsonConverter 仅用于水果列表中的对象?

【问题讨论】:

  • 我猜你可以在IFruit 接口或Fruit 成员上使用JsonConverterAttribute。
  • 是的,当然。就这么简单。接口定义上的属性。谢谢! (如果您希望将此标记为最佳答案,请随时在下面重复。)
  • 没关系,我真的只是给了你一个提示。您可以自己发布答案并接受。

标签: c# json json.net


【解决方案1】:

问题的解决方法很简单,真的。

[JsonConverter (typeof(IFruitConverter))]
public interface iFruit
    {

    }

作为旁注,转换器基于this answer。 我在返回false 的转换器中添加了CanWrite 覆盖,这样它在序列化过程中将被忽略,仅在反序列化过程中发挥作用。 感谢@Blorgbeard!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-13
    • 2013-07-28
    • 2010-11-11
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    相关资源
    最近更新 更多