我正在尝试将以下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);
}
答案 0 :(得分:0)
您的考试部分数据数组不在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可以处理单引号,但其他解析器可能不会那么宽容。