-1

I have an issue that I can't seem to solve.

I have the following class

public class Foo:IFoo
{
  Private List<IBar> _listTest=new List<IBar>();

  Public List<IBar> ListTest
  {
    get
    {
      return _listTest;
    }
    set
    {
      _listTest=value;
    }
  }
}

When I make a webapi call from an mvc app and it tries to deserialise it I get the following error

JsonSerializationException: Could not create an instance of type IBar. Type is an interface or abstract class and cannot be instantiated.

I know this can be fixed by changing the return type of the list in the interface to List but that seems like it is not a great idea.

What is the best way to get this to deserialise?

coolblue2000
  • 3,796
  • 10
  • 41
  • 62
  • Have you looked at [JSON.NET - how to deserialize collection of interface-instances?](https://stackoverflow.com/q/15880574) or [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752) or [Using Json.NET converters to deserialize properties](https://stackoverflow.com/q/2254872) or [How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?](https://stackoverflow.com/q/8030538) or [how to deserialize JSON into IEnumerable with Newtonsoft JSON.NET](https://stackoverflow.com/q/6348215)? – dbc Apr 05 '18 at 22:14

1 Answers1

0

You didn't mention of used serializer, so it's propably JSON.NET :)

People may agree or not but in my opinion using interfaces in sertialized object should be avoided. For example, It's much harder to change serializer when interfaces are flying around.

but

public class Foo : IFoo
{
    [JsonConverter(typeof(JsonKnowType<List<SomeBarImp>>))]
    public List<IBar> ListTest { get; set; }
}

with

public class JsonKnowType<TConcrete> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return serializer.Deserialize<TConcrete>(reader);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

may be useful for you.

But as u can notice, type is explicitly defined at the end.

adobrzyc
  • 195
  • 1
  • 8