How to create an instance of an object?

I am using the Json.Net library to convert objects to json and back to objects.

I have an interface:

public interface IGoods { List<IPen> Pens { get; set; } List<IPencil> Pencils{ get; set; } void Deserialize(String json); } 

implementation:

 new public void Deserialize(String json) { JsonConvert.DeserializeObject<Goods>(json); } 

Obvious error I received: Failed to create an instance of type Project.IPen. A type is an interface or an abstract class and cannot be created.

How to overcome this error?

Thanks!

+4
source share
3 answers

According to the documentation, you need to write some logic to tell Json.Net how to make object creation - http://james.newtonking.com/projects/json/help/CustomCreationConverter.html

+1
source

IPen is an interface, not a class, which means that it cannot be created. Basically you need a class that implements the IPen interface (let's call it Pen). You can then replace IPen in the Json string with Pen, and Json.Net will be able to instantiate the object.

To be clear, your Pen class should look something like this:

 public class Pen: IPen { //Interface implementation here. } 
0
source

Source: https://habr.com/ru/post/1332836/


All Articles