我正在尝试将下面的json字符串转换为对象列表。我收到一个错误。你能帮忙吗?
string jsonp = @"{
'data': [ { 'SectionId':1,'Name':'Bachelor ','NavigationRoute':'applicantExam/education','Position':15,IsEducation':true,'IsEducationCollegeDegree':null,'previousSection':null,'nextSection':null,'IsCurrent':null,'SectionCompleted':null},
{ 'SectionId':2,'Name':'Master','NavigationRoute':'applicantExam/education','Position':20,'IsEducation':true,'IsEducationCollegeDegree':null,'previousSection':null,'nextSection':null,'IsCurrent':null,'SectionCompleted':null} ]
}";
ExamSectionModel[] m = JsonConvert.DeserializeObject<ExamSectionModel[]>(jsonp);
foreach( var x in m)
{
Console.WriteLine(x.Name);
}
您的考试部分数据数组不在JSON的根级别;这是data
酒店内的一层楼。要解决此问题,您需要创建一个包装器类,然后反序列化为该类:
public class RootObject
{
public ExamSectionModel[] Data { get; set; }
}
public class ExamSectionModel
{
public int SectionId { get; set; }
public string Name { get; set; }
public string NavigationRoute { get; set; }
public int Position { get; set; }
public bool IsEducation { get; set; }
public bool? IsEducationCollegeDegree { get; set; }
public object previousSection { get; set; }
public object nextSection { get; set; }
public bool? IsCurrent { get; set; }
public bool? SectionCompleted { get; set; }
}
然后:
RootObject root = JsonConvert.DeserializeObject<RootObject>(jsonp);
foreach(var x in root.Data)
{
Console.WriteLine(x.Name);
}
小提琴:https : //dotnetfiddle.net/TUFouk
顺便说一句,您的JSON似乎在第一行'Position':15,
之前和之后缺少引号IsEducation':true
。我假设这只是问题的错字,但是如果不是,您将需要在JSON中修复它,否则它将无法解析。
同样,从技术上讲,您应该在JSON中使用双引号,而不是单引号,以符合标准。(请参阅JSON.org。)JSON.net可以处理单引号,但其他解析器可能不会那么宽容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句