序列化接口对象列表 [英] Serializing a list of interface objects

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

问题描述

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

Using Json.net, I want to deserialize a basket containing interface objects. This...

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

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

... should go into this...

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

无法实例化接口,因此需要转换为具体对象.我发现了使用JsonConverter创建具体的Apple和Pear实例的示例.但是,列表总是直接用以下行创建:

Interfaces cannot be instantiated, so a conversion to concrete objects is needed. I found examples using a JsonConverter to create concrete Apple and Pear instances. But the list is always created directly with a line like:

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

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

How do I deserialize a whole Basket, where the JsonConverter is used only for the objects in the fruit list?

推荐答案

问题的解决方法确实很简单.

The solution to the problem is simple, really.

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

    }

作为旁注,转换器基于此答案. 我在返回false的转换器中添加了CanWrite覆盖,因此在序列化期间它将被忽略,仅在反序列化期间起作用. 感谢@Blorgbeard!

As a sidenote, the converter is based on this answer. I added a CanWrite override to the converter that returns false, so that it will be ignored during serialization and only come into play during deserialisation. Thanks to @Blorgbeard!

这篇关于序列化接口对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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