問題描述
我正在嘗試設置一個閱讀器,它將接收來自各種網站的 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
會產生錯誤:
無法創建 IThingy 類型的實例.類型是接口或抽象類,不能實例化.
Could not create an instance of type IThingy. Type is an interface or abstract class and cannot be instantiated.
相對于 Thingy,讓它成為 IThingy 相對重要,因為我正在處理的代碼被認為是敏感的,并且單元測試非常重要.對于像 Thingy 這樣成熟的對象,無法模擬原子測試腳本的對象.它們必須是一個接口.
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 在 相關問題,我這里總結一下.
@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; }
}
這篇關于在 JSON.NET 中反序列化的轉換接口的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!