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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.