-1

I am looking at some JSON data, which looks like this (the data values are hypothetical):

{
    "students": [
        {
            "Class": "Mr Smith",
            "Student": [
                "Mark Williams",
                15,
                "1 The Street London",
                "Maths",
                "Football",
                "Tennis"
            ]
        },
    {
            "Class": "Ms Morgan",
            "Student": [
                "Jenny Phillips",
                12,
                "1 The Farm London",
                "English",
                "Netball",
                "Football"
            ]
        }
    ],
    "total": 2
}

I am trying to get the students into a class, which looks something like this:

public class Student
{
   public string Name {get; set}
   public int Age {get; set}
   public string Address {get; set}
}

Notice the following:

1) There is a root element (Students), which is irrelevant. 2) There is what appears to be a footer element (total), which is irrelevant. What is the correct terminology for the "footer" element? 3) Address; favourite subject; favourite sport and least favourite sport are irrelevant i.e. only name; age and address are relevant.

I have spent the last few hours trying to get this work with Newtonsoft e.g. I have tried this:

List<Student> students = JsonConvert.DeserializeObject<Student>(json);

How can I deserialise this with Newtonsoft? Ihave spent the last three hours trying to do this, but haven't managed it.

w0051977
  • 15,099
  • 32
  • 152
  • 329

2 Answers2

3

You could use Json.Net's LINQ-to-JSON API (JObjects) to get the data into your list of students:

var jo = JObject.Parse(json);

List<Student> students = jo["students"]
    .Select(t => t["Student"])
    .Select(s => new Student
    {
        Name = (string)s[0],
        Age = (int)s[1],
        Address = (string)s[2]
    })
    .ToList();

Fiddle: https://dotnetfiddle.net/GzS9vj

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

You can write Custom Json Converter as per the requirement. You may take help from newtonsoft site: https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm