0

My code:

var configuration = await Task.Factory.StartNew(() =>
    JsonConvert.DeserializeObject<IConfigurationService>(json));

fails at run-time with the error:

Newtonsoft.Json.JsonSerializationException: 'Could not create an instance of type .....IConfigurationService. Type is an interface or abstract class and cannot be instantiated. Path 'MyProperty', line 2, position 25.'

If I replace the IConfigurationService with the concrete version (that implements IConfigurationService) like so:

var configuration = await Task.Factory.StartNew(() =>
    JsonConvert.DeserializeObject<ConfigurationService>(json));

It works fine. But that defeats the object of using an interface. How can I get the deserialise to work with the interface?

Assume IConfigurationService is this simple:

public interface IConfigurationService
{
    string MyProperty{ get; set; }
}

I have looked on the Web and it seems I need to use a JsonConverter, however all of the examples relate to MyProperty being an Interface.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Rob L
  • 2,124
  • 3
  • 22
  • 50
  • 2
    One way or another you need to specify the concrete class to instantiate. The standard solution is to use a subclass of `CustomCreationConverter`. See e.g. [NewtonSoft.Json Serialize and Deserialize class with property of type `IEnumerable`](https://stackoverflow.com/q/11754633/3744182). The solution applies equally whether the interface is the *root type* or some *nested type*. – dbc Jul 28 '19 at 02:47
  • 2
    Does that answer work for you, or do you still have a problem? If you still have a problem, can you explain what it is? – dbc Jul 28 '19 at 19:17
  • 2
    An interface can't exist in a vacuum - it simply describes a behavior, a contract. Something must be there to implement it, and that something must be chosen when you deserialize. – 500 - Internal Server Error Jul 28 '19 at 19:25

1 Answers1

0

I decided I did not need the interface. I just used the concrete class. Thank you for all of the help.

Rob L
  • 2,124
  • 3
  • 22
  • 50