Serializing a list of interface objects

可紊 提交于 2019-12-25 07:16:20

问题


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,...
}

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());

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


回答1:


The solution to the problem is simple, really.

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

    }

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!



来源:https://stackoverflow.com/questions/38087709/serializing-a-list-of-interface-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!