c# - 在 JSON.NET 中反序列化的转换接口(interface)

我正在尝试设置一个阅读器,它将接收来自各种网站的 JSON 对象(想想信息抓取)并将它们翻译成 C# 对象。我目前正在使用 JSON.NET 进行反序列化过程。我遇到的问题是它不知道如何处理类中的接口(interface)级属性。所以自然的东西:

public IThingy Thing

会产生错误:

Could not create an instance of type IThingy. Type is an interface or abstract class and cannot be instantiated.

相对于 Thingy,让它成为 IThingy 相对重要,因为我正在处理的代码被认为是敏感的,并且单元测试非常重要。对于像 Thingy 这样成熟的对象,无法模拟原子测试脚本的对象。它们必须是一个接口(interface)。

我已经研究 JSON.NET 的文档一段时间了,我在这个网站上找到的与此相关的问题都是一年多以前的。有什么帮助吗?

另外,如果重要的话,我的应用程序是用 .NET 4.0 编写的。

最佳答案

@SamualDavis 在 related question 中提供了一个很好的解决方案,我将在这里总结一下。

如果您必须将 JSON 流反序列化为具有接口(interface)属性的具体类,则可以将具体类作为参数包含到该类的构造函数中! NewtonSoft 反序列化器足够聪明,可以计算它需要使用那些具体的类来反序列化属性。

这是一个例子:

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; }
}

https://stackoverflow.com/questions/5780888/

相关文章:

python - json.load() 和 json.loads() 函数有什么区别

c# - ASP.NET Core 返回带有状态码的 JSON

json - 如何在结构中定义多个名称标签

json - 如何在 Swift 中解码 HTML 实体?

javascript - 通过 JavaScript 动态创建 JSON 对象(没有连接字符串)

json - 如何在 ECMAScript 6 中导入 JSON 文件?

javascript - JSON.parse 意外字符错误

android - 如何在 Android 中使用 HTTPClient 以 JSON 格式发送 P

android - 如何在 Android 中解析 JSON?

javascript - 从AngularJS中的对象数组中通过id获取特定对象