JSON.NET 中反序列化的转换接口 [英] Casting interfaces for deserialization in JSON.NET

查看:14
本文介绍了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

会产生错误:

无法创建类型为 IThingy 的实例.类型是接口或抽象类,不能被实例化.

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

将它设为 IThingy 相对于 Thingy 相对重要,因为我正在处理的代码被认为是敏感的,并且单元测试非常重要.对于像 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 中反序列化的转换接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆