铸件反序列化接口,JSON.NET
我想建立一个读者,将采取从各种网站JSON对象(思信息刮),并将其转化为C#对象。我目前使用JSON.NET的反序列化过程我。我遇到的问题是,它不知道如何在一个类处理接口级属性。因此,一些的性质:
I am trying to set up a reader that will take in JSON objects from various websites (think information scraping) and translate them into C# objects. I am currently using JSON.NET for the deserialization process. The problem I am running into is that it does not know how to handle interface-level properties in a class. So something of the nature:
public IThingy Thing
会产生错误:
Will produce the error:
无法创建类型IThingy的一个实例。类型是一个接口或抽象类和不能实例
Could not create an instance of type IThingy. Type is an interface or abstract class and cannot be instantiated.
这是比较重要的是有它是一个IThingy因为code我的工作被认为是敏感的,单元测试是非常重要的,而不是一啄。惩戒用于原子测试脚本对象是不可能的,就像啄完全成熟的对象。它们必须是接口
It is relatively important to have it be an IThingy as opposed to a Thingy since the code I am working on is considered sensitive and unit testing is highly important. Mocking of objects for atomic test scripts is not possible with fully-fledged objects like Thingy. They must be an interface.
我一直在钻研JSON.NET的文档有一段时间了,而与此相关的问题,我能找到在这个网站都是从一年前。任何帮助?
I've been poring over JSON.NET's documentation for a while now, and the questions I could find on this site related to this are all from over a year ago. Any help?
另外,如果它很重要,我的应用程序是用.NET 4.0。
Also, if it matters, my app is written in .NET 4.0.
@SamualDavis设置在related问题,我将在这里总结一下。
@SamualDavis provided a great solution in a related question, which I'll summarize here.
如果你有反序列化一个JSON流成具有界面特性的具体类,你可以的包括具体类作为参数传递给类构造函数!的的NewtonSoft解串器是足够聪明的身影指出,它需要使用这些具体的类反序列化的属性。
If you have to deserialize a JSON stream into a concrete class that has interface properties, you can include the concrete classes as parameters to a constructor for the class! The NewtonSoft deserializer is smart enough to figure out that it needs to use those concrete classes to deserialize the properties.
下面是一个例子:
public class Visit : IVisit
{
/// <summary>
/// This constructor is required for the JSON deserializer to be able
/// to identify concrete classes to use when deserializing the interface properties.
/// </summary>
public Visit(MyLocation location, Guest guest)
{
Location = location;
Guest = guest;
}
public long VisitId { get; set; }
public ILocation Location { get; set; }
public DateTime VisitDate { get; set; }
public IGuest Guest { get; set; }
}