0

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?

Erik Bongers
  • 416
  • 2
  • 10
  • 2
    I'm guessing you could use a [`JsonConverterAttribute`](http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverterAttribute.htm) either on the `IFruit` interface or the `Fruit` member. – Blorgbeard Jun 28 '16 at 23:14
  • Yes, of course. It's as simple as that. Attribute on the interface definition. Thank you! (if you want this marked as best answer, feel free to repeat it below.) – Erik Bongers Jun 28 '16 at 23:43
  • That's alright, I really just gave you a hint. You could post an answer yourself and accept it. – Blorgbeard Jun 29 '16 at 01:08

1 Answers1

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!

Community
  • 1
  • 1
Erik Bongers
  • 416
  • 2
  • 10