【发布时间】:2019-04-01 17:24:14
【问题描述】:
我有这个我正在尝试反序列化的 JSON:
{
"events": [
{
"eventName": "service-review-created",
"version": "1",
"eventData": {
"id": "XXXXXXbca843690a3015d3c0",
"language": "en",
"stars": 5,
"title": "I was particularly impressed by the...",
"text": "I was particularly impressed by the...",
"referenceId": null,
"createdAt": "2019-03-29T23:05:32Z",
"link": "https://api.trustpilot.com/v1/reviews/XXX",
"consumer": {
"id": "XXXXXX40000ff000a74b9e1",
"name": "XXX",
"link": "https://api.trustpilot.com/v1/consumers/5899b3140000ff000a74b9e1"
}
}
}
]
}
这些是我的模型:
public class Event
{
public string eventName { get; set; }
public string version { get; set; }
public EventData eventData { get; set; }
}
public class EventData
{
public string id { get; set; }
public string language { get; set; }
public int stars { get; set; }
public string title { get; set; }
public string text { get; set; }
public string referenceId { get; set; }
public DateTime createdAt { get; set; }
public string link { get; set; }
public Consumer consumer { get; set; }
}
public class Consumer
{
public string id { get; set; }
public string name { get; set; }
public string link { get; set; }
}
当我尝试时:
List<Event> events = JsonConvert.DeserializeObject<List<Event>>(jsonstring);
我明白了:
无法反序列化当前的 JSON 对象(例如 { “名称”:“价值” } ) 转换为 'System.Collections.Generic.List`1[LambdaFeedFunctions.Trustpilot.Models.Event]' 类型,因为该类型需要 JSON 数组(例如 [1,2,3])才能正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像可以从 JSON 对象反序列化的数组或列表。 JsonObjectAttribute 也可以添加到类型中,以强制它从 JSON 对象反序列化。
我不确定我需要进行哪些更改才能使其正常工作。
【问题讨论】:
-
您缺少
RootObject。将 JSON 粘贴为类将为您解决这个问题。 -
Visual Studios paste special 功能的替代方法是json2csharp。这将为给定的 json 字符串生成适当的类模型。