json - Newtonsoft.DeserializeObject 用于泛型类

标签 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 string code { get; set; }
    public T data { get; set; }
    public long ts { get; set; }
}

所以这个类将映射每个变量。但data部分可以是通用的,即它可能具有不同的格式,而不是2个变量ab

所以我创建了另一个类

public class DTProf
{
    public string a { get; set; }
    public string b { get; set; }
}

在我的代码中,我调用为

DTWSResponse<DTProf> prof = JsonConvert.DeserializeObject<DTWSResponse<DTProf>>(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.

有什么想法吗?

最佳答案

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

显示的 JSON 具有 data 属性的集合。因此,使用集合作为类型参数。无需更改通用类。

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

关于json - Newtonsoft.DeserializeObject 用于泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51434894/

相关文章:

java - JSON 数组到 ArrayList<List<String>>

javascript - 如何在没有重定向页面的情况下使用 jquery post 发送大数据?

c# - 如何将自定义列表类转换为json?

javascript - jQuery get 函数中的 AJAX 请求、变量问题

javascript - 如何设置安全规则以防止删除 firebase 中的数据?

ios - Objective-c 中的 NSTaggedPointerString objectForKey

c# - Json.NET 反序列化 Dictionary<uint, T> 并执行转换

javascript - 如何保留数字中的前导零?

c# - 如何捕获 JsonConverter 属性中抛出的异常?

c# - 如何转换 JToken