【发布时间】:2020-10-19 10:04:02
【问题描述】:
我收到了来自 OData api 的响应,如下所示。我只想让 api 返回一个只有三个字段的对象列表(即)[datetime]、[body]、[subject]。
{
"d": {
"results": [
{
"__metadata": {
"id": "http://localhost:7305",
"uri": "http://localhost:7305",
"type": "Subject.Classifications"
},
"dateTime": "2020-06-25T11:31:51",
"source": "JHGTY",
"body": "The offering has now increased ",
"subject": "Offering- updated",
"Error": {
"__deferred": {
"uri": "http://localhost:7305/"
}
}
},
{
"__metadata": {
"id": "http://localhost:7305",
"uri": "http://localhost:7305",
"type": "Subject.Classifications"
},
"dateTime": "2020-06-26T11:25:51",
"source": "XFGFT",
"body": "The offering has now degraded ",
"subject": "Offering- updated",
"Error": {
"__deferred": {
"uri": "http://localhost:7305/"
}
}
}
]
}
}
我创建了如下模型:
public class Classification
{
public DateTime dateTime { get; set; }
public string body { get; set; }
public string subject { get; set; }
}
我正在尝试反序列化响应,以便它可以返回一个列表,但是当我使用下面的代码时它会抛出一个无法反序列化的异常:
IRestResponse response = client.Execute(request);
List<Classification> classifications = JsonConvert.DeserializeObject<List<Classification>>(response.Content);
我得到的例外是:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[genie.Api.Controllers.ClassificationController+Classifications]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为正常的 .NET 类型(例如,不是像整数这样的原始类型,而不是可以从 JSON 对象反序列化的集合类型(如数组或列表)。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径“d”,第 1 行,位置 5。
【问题讨论】:
-
你能否也包括你得到的错误。
-
在此处查看 4 个赞成的答案stackoverflow.com/questions/17671539/…
-
这能回答你的问题吗? How to get only some fields from a JSON?