-1

I am trying to convert the below json string to a list of object. I am getting an error. Can you please help?

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);
 }
Jim Hewitt
  • 1,726
  • 4
  • 24
  • 26
user2465036
  • 351
  • 2
  • 11
  • 24
  • I think this link could help you: http://stackoverflow.com/questions/19581820/how-to-convert-json-array-to-list-of-objects-in-c-sharp – Masoud Sedghi Aug 30 '16 at 15:53

1 Answers1

0

Your exam section data array is not at the root level in the JSON; it is one level down, inside the data property. To fix, you need to make a wrapper class and then deserialize into that:

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; }
}

Then:

RootObject root = JsonConvert.DeserializeObject<RootObject>(jsonp);
foreach(var x in root.Data)
{
    Console.WriteLine(x.Name);
}

Fiddle: https://dotnetfiddle.net/TUFouk

As an aside, your JSON appears to be missing a quote after 'Position':15, and before IsEducation':true on the first line. I'm assuming that is just a typo in the question, but if not, you'll need to fix that in your JSON or it will fail to parse.

Also, you should technically be using double quotes in your JSON, not single quotes, to be conformant with the standard. (See JSON.org.) JSON.net can handle the single quotes, but other parsers might not be so forgiving.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300