Json 泛型类的Newtonsoft.DeserializeObject

Json 泛型类的Newtonsoft.DeserializeObject,json,json.net,Json,Json.net,我有一个JSON响应,如下所示 { "msg": "1", "code": "2", "data": [ { "a": "3", "b": "4" } ], "ts": "5" } 我想创建一个泛型类 public class DTWSResponse<T> { public string msg { get; set; } public stri

我有一个JSON响应,如下所示

{
    "msg": "1",
    "code": "2",
    "data": [
        {
            "a": "3",
            "b": "4"
        }
    ],
    "ts": "5"
}
我想创建一个泛型类

public class DTWSResponse<T>
{
    public string msg { get; set; }
    public string code { get; set; }
    public T data { get; set; }
    public long ts { get; set; }
}
在我的代码中,我调用

DTWSResponse<DTProf> prof = JsonConvert.DeserializeObject<DTWSResponse<DTProf>>(json);
DTWSResponse prof=JsonConvert.DeserializeObject(json);
但是我得到了以下错误

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code

Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'DataTransfer.DTProfile' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

Path 'data', line 1, position 40.
在Newtonsoft.Json.dll中发生“Newtonsoft.Json.JsonSerializationException”类型的异常,但未在用户代码中处理
其他信息:无法将当前JSON数组(例如[1,2,3])反序列化为类型“DataTransfer.DTProfile”,因为该类型需要一个JSON对象(例如{“name”:“value”})才能正确反序列化。
要修复此错误,请将JSON更改为JSON对象(例如{“name”:“value”}),或将反序列化类型更改为数组或实现可从JSON数组反序列化的集合接口(例如ICollection、IList)类似列表的类型。还可以将JsonArrayAttribute添加到类型中,以强制它从JSON数组反序列化。
路径“数据”,第1行,位置40。

有什么想法吗?

数据
列成一个通用的列表,你应该很好

public class DTWSResponse<T>
{
    public string msg { get; set; }
    public string code { get; set; }
    public IList<T> data { get; set; }
    public long ts { get; set; }
}
公共类DTWSResponse
{
公共字符串msg{get;set;}
公共字符串代码{get;set;}
公共IList数据{get;set;}
公共长ts{get;set;}
}

为泛型类型参数使用正确的类型

显示的JSON包含一个
数据
属性的集合。因此,请使用集合作为类型参数。无需更改泛型类

var prof = JsonConvert.DeserializeObject<DTWSResponse<IList<DTProf>>>(json);
var a = prof.data[0].a;
var prof=JsonConvert.DeserializeObject(json);
var a=prof.data[0].a;

“数据”
是一个数组,但您试图将其映射到类型为
T
对象。请尝试使用
public-IList-data{get;set;}
代替…为泛型类型参数
prof=JsonConvert.DeserializeObject(json)使用正确的类型DTWSResponse
类不变,并使用
List
作为数据类型。
var prof = JsonConvert.DeserializeObject<DTWSResponse<IList<DTProf>>>(json);
var a = prof.data[0].a;