[英]Serializing a list of interface objects
Using Json.net, I want to deserialize a basket containing interface objects. 我想使用Json.net反序列化包含接口对象的篮子。 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.
我发现了使用JsonConverter创建具体的Apple和Pear实例的示例。 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? 如何反序列化整个购物篮,其中JsonConverter仅用于水果列表中的对象?
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. 我向返回
false
的转换器添加了CanWrite
覆盖,以便在序列化期间将其忽略,仅在反序列化期间起作用。 Thanks to @Blorgbeard! 感谢@Blorgbeard!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.