C# 无法将JSON对象反序列化到列表中
我有以下课程:C# 无法将JSON对象反序列化到列表中,c#,json,C#,Json,我有以下课程: public class Datum { public bool Prop1 { get; set; } public bool Prop2 { get; set; } public bool Prop3 { get; set; } public bool Prop4 { get; set; } public bool Prop5 { get; set; } public bool Prop6 { get; set; } } pu
public class Datum
{
public bool Prop1 { get; set; }
public bool Prop2 { get; set; }
public bool Prop3 { get; set; }
public bool Prop4 { get; set; }
public bool Prop5 { get; set; }
public bool Prop6 { get; set; }
}
public class Example
{
public IList<Datum> data { get; set; }
}
我使用Netonsoft JSON.NET将JSON反序列化为C#对象,如下所示:
var items=JsonConvert.DeserializeObject(json)代码>
但我得到了以下错误:
Newtonsoft.Json.JsonSerializationException:'无法将当前Json对象(例如{“名称”:“值”})反序列化为'System.Collections.Generic.List`1[ReadJson.Example]”类型,因为该类型需要Json数组(例如[1,2,3])才能正确反序列化。
若要修复此错误,请将JSON更改为JSON数组(例如[1,2,3]),或更改反序列化类型,使其成为可以从JSON对象反序列化的正常.NET类型(例如,不是integer之类的基元类型,也不是数组或列表之类的集合类型)。还可以将JsonObjectAttribute添加到类型中,以强制它从JSON对象反序列化。
路径“数据”,第1行,位置8'
我在一些在线c#编辑器中运行了完全相同的代码,这很好。但是当我在本地的Visual Studio中尝试时,它给出了错误。我使用的是Newtonsoft版本12及以上
谁能解释一下我的代码有什么问题吗
提前感谢。您没有示例的列表。您有一个示例
,单数<代码>示例
具有数据
属性;JSON只包含该属性的一个实例,其封闭对象不在数组中
所以
JsonConvert.DeserializeObject(json)
var json = @"{'data': [
{
'Prop1': true,
'Prop2': true,
'Prop3': true,
'Prop4': true,
'Prop5': true,
'Prop6': true
},
{
'Prop1': true,
'Prop2': true,
'Prop3': true,
'Prop4': true,
'Prop5': true,
'Prop6': false
},
{
'Prop1': false,
'Prop2': true,
'Prop3': true,
'Prop4': true,
'Prop5': false,
'Prop6': false
},
{
'Prop1': false,
'Prop2': true,
'Prop3': true,
'Prop4': false,
'Prop5': false,
'Prop6': false
}]
}";
JsonConvert.DeserializeObject<Example>(json)