Erik Bongers
Erik Bongers

Reputation: 462

Serializing a list of interface objects

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?

Upvotes: 0

Views: 2415

Answers (1)

Erik Bongers
Erik Bongers

Reputation: 462

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!

Upvotes: 1

Related Questions