我正在try 建立一个阅读器,它将从各种网站(比如信息抓取)接收JSON对象,并将它们转换为C#对象.我目前正在使用JSON.NET进行反序列化过程.我遇到的问题是,它不知道如何处理类中的接口级属性.这是自然现象:

public IThingy Thing

Will produce the error:

无法创建I类型的实例.类型是接口或抽象类,无法实例化.

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文档已经有一段时间了,我在这个站点上可以找到的与此相关的问题都是一年多前的.有什么帮助吗?

另外,如果有必要的话,我的应用程序是用英文写的.NET 4.0.

推荐答案

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

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相关问答推荐

您可以使用Jolt对JSON执行OR条件吗

PowerShell脚本未按预期生成预期的JSON输出

解析JSON说函数parse_json不存在?

盒子图显示不正确

Allof Indide的JSON模式之一

如何用JQ更改空/布尔/数字的 colored颜色 ?

在Vega中如何通过滑块改变条形图的宽度

(Kotlin)com.google.gson.internal.LinkedTreeMap无法转换为com.example.phonetest2.model.HallData

Jolt:数组中两个字符串的连接

未知的META规范,无法验证.[规范v1.0.1]

基于JQ中另一个对象的值 Select 对象

使用本地 JSON api react TS Axios

Shell脚本空格转义

JOLT 在 struct 体中间添加一个 JSON 字段

如何将任意 json 对象发布到 webapi

Jackson Json:如何将数组转换为 JsonNode 和 ObjectNode?

如何将 LinkedHashMap 转换为自定义 java 对象?

使用 JSONObject 在 Java 中为以下 struct 创建嵌套 JSON 对象?

可以在 SharedPreferences 中保存 JSON 数组吗?

从 Json 对象 Android 中获取字符串值