【发布时间】:2020-02-20 10:19:23
【问题描述】:
我有以下 C# 类结构,
public class Event
{
public string Id { get; set; }
public Body Body { get; set; }
public BodyProperty[] BodyProperties { get; set; }
public string EventType { get; set; }
public string CreatedTime { get; set; }
}
public class BodyProperty
{
public string Key { get; set; }
public string Value { get; set; }
}
public class Body
{
public Body(string value, string type = "TextualBody", string format = "application/json")
{
Type = type;
Value = value;
Format = format;
}
public string Type { get; set; }
public string Value { get; set; }
public string Format { get; set; }
}
并尝试读取下面的 JSON 文件,
{
"Events": [
{
"Id": "d22fc23c-968f-4406-bebb-fca231694986",
"Body": {
"Type": "TextualBody",
"Value": "test",
"Format": "application/json"
},
"BodyProperties": null,
"EventType": "Entity",
"CreatedTime": "2020-02-20T13:57:14.1234165+05:30"
},
{
"Id": "fgdgdg-968f-4406-bebb-646464",
"Body": {
"Type": "TextualBody",
"Value": "test",
"Format": "application/json"
},
"BodyProperties": null,
"EventType": "Entity",
"CreatedTime": "2020-02-21T13:57:14.1234165+05:30"
}
]
}
但是在尝试这样阅读时会出现以下错误,我无法更改 JSON 格式,阅读时我可以更改什么?
using (StreamReader file = File.OpenText(@"C:\TEMP\json1.json"))
using (JsonTextReader jsonreader = new JsonTextReader(file))
{
var serializer = new JsonSerializer();
return serializer.Deserialize<List<Event>>(jsonreader);
}
Newtonsoft.Json.JsonSerializationException: '无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[uploadJSON.Event]' 因为该类型需要正确反序列化的 JSON 数组(例如 [1,2,3])。 要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。
【问题讨论】: