How to create instance of an object?
I am using 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);
}
The obvious error I got is: Could not create an instance of type Project.IPen. Type is an interface or abstract class and cannot开发者_JAVA百科 be instantated.
How do I overcome this error?
Thanks!
According to the documentation you need to write some logic to tell Json.Net how to do the object creation - http://james.newtonking.com/projects/json/help/CustomCreationConverter.html
See Using Json.NET converters to deserialize properties
IPen is an interface, not a class, which means it cannot be instantiated. Basically what you need is a class which implements the IPen interface (let's call it Pen). You should then be able to replace IPen in the Json string with Pen, and Json.Net will be able to instantiate the object.
Just to be clear, your Pen class should look something like this:
public class Pen: IPen
{
//Interface implementation here.
}
精彩评论