在 JSON.NET 中反序列化的转换接口

时间:2023-04-27
本文介绍了在 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.

相对于 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 中反序列化的转换接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Json.NET 可以对流进行序列化/反序列化吗? 下一篇:如何将 JSON 反序列化为 IEnumerable&lt;BaseType&gt;使用 Newtons

相关文章