我有以下课程:
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; }
}我在变量中有下面的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
}]
}";我使用Netonsoft JSON.NET将JSON反序列化为C#对象,如下所示:
var items = JsonConvert.DeserializeObject<List<Example>>(json);,但我得到了以下错误:
'System.Collections.Generic.List`1ReadJson.Example‘:’无法将当前JSON对象(例如,{“名称”:“值”})反序列化为类型Newtonsoft.Json.JsonSerializationException,因为该类型需要一个JSON数组(例如,1、2、3)才能正确反序列化。要修复此错误,要么将JSON更改为JSON数组(例如,1,2,3),要么更改反序列化类型,使之成为可以从JSON对象反序列化的普通.NET类型(例如,不像整数这样的原始类型,而不是数组或列表之类的集合类型)。还可以将JsonObjectAttribute添加到类型中,以强制它从JSON对象反序列化。路径'data',第1行,位置8‘
我在一些在线c#编辑器中运行了完全相同的代码,这很好。但是,当我在本地中尝试时,它会出现错误。我使用的是Newtonsoft版本12及以上。
有人能解释我的密码出了什么问题吗。
提前谢谢。
发布于 2019-09-25 15:17:37
您没有Example列表。你有一个Example,单数。Example有一个data属性;您的JSON只包含该属性的一个实例,其封闭对象不在数组中。
所以,
JsonConvert.DeserializeObject<Example>(json)https://stackoverflow.com/questions/58101660
复制相似问题