铸件反序列化接口,JSON.NET [英] Casting interfaces for deserialization in JSON.NET

查看:297
本文介绍了铸件反序列化接口,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设置在<一个很好的解决方案href="http://stackoverflow.com/questions/2254872/using-json-net-converters-to-deserialize-properties">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; }
}

这篇关于铸件反序列化接口,JSON.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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