0

I have a JSON file which I want to deserialize. I am very new to JSON and Deserialization in general and have found this quite challenging . My JSON file structure is as follows ,

{
"SchoolName": "ThisIsTheSchoolName",
  "Student": [
    {
      "Id": "s001",
      "Name": "ABC"
    },
    {
      "Id": "s002",
      "Name": "CDE"
    },
    {
      "Id": "s003",
      "Name": "EFG"
    },
    {
      "Id": "s004",
      "Name": "GHI"
    },
    {
      "Id": "s005",
      "Name": "IJK"
    }
]
}

What I am trying to do is first store the "SchoolName" as a variable ( Which I will need later on in my application) . Secondly I want to iterate through the JSON list "Student" and store every value in "Id" in a List and Every Value in "Name" in another List . I was not able to fathom a way to do this . Here is what I have been able to try so far (Which )

    string filePath = @"D:\Projects\Student.json";
    string data = File.ReadAllText(filePath);
    Console.Write(data);

    Console.ReadLine();

    dynamic stuList= JsonConvert.DeserializeObject(data);
    foreach (var item in stuList)
    {

        //string Id = item.Id;
        //string Name= item.Version;
    }

Would really appreciate some help or direction to something that I can get a head start on this

Devin
  • 239
  • 1
  • 2
  • 9
  • 1
    https://stackoverflow.com/questions/34302845/deserialize-json-into-object-c-sharp – xdtTransform Nov 18 '19 at 09:30
  • 1
    https://stackoverflow.com/questions/25052293/deserialize-json-to-c-sharp-classes – xdtTransform Nov 18 '19 at 09:30
  • Your first misconception is that you will get a list of something. You get an object with two Properties: "SchoolName" and "Student" which is a List of Object with two Properties: "Id" and "Name". – Fildor Nov 18 '19 at 09:31
  • Possible duplicate of [Deserialize JSON into Object C#](https://stackoverflow.com/questions/34302845/deserialize-json-into-object-c-sharp) – Robin B Nov 18 '19 at 09:33
  • I don't understand the Idea of 2 independant list storing Names and Ids when they are linked in the source data. You understand that you may mess up the link between those 2 things. – xdtTransform Nov 18 '19 at 09:34

2 Answers2

3

In Visual Studio there is an option called Paste Special using which we can generate the C# side pay load for the json object which will be :

public class Student
{
    public string Id { get; set; }
    public string Name { get; set; }
}

public class StudentsInformation
{
    public string SchoolName { get; set; }
    public List<Student> Student { get; set; }
}

and then can be used to deserialize like:

var studentsInformation = JsonConvert.DeserializeObject<StudentsInformation>(data);

and now the studnets list can be directly used :

var schoolName = studentsInformation.SchoolName;
var students = studentsInformtaion.Student;
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • Thanks for your answer @Ehsan I am actually encountering a couple of problems tho First one being I am getting a run time exception => **Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: {. Path 'students', line 4, position 5.' ** . I am not sure wheeather it is a problem with the JSON file . Can you kindly have a look at the JSON structure that is in the Question and let me know if it is because of the JSON file or something wrong with the code ? – Devin Nov 18 '19 at 10:52
  • Second one I cant seem to understand where the values are being added to a List or something like that ? (for this I can figure out if I play around with the code a lil but for me to do so I ned to figure out this runtime error I am getting) Thanks again for your help thus far – Devin Nov 18 '19 at 10:53
  • The exception is thrown in this line var studentsInformation = JsonConvert.DeserializeObject(data); – Devin Nov 18 '19 at 11:11
  • it is json issue in your file – Ehsan Sajjad Nov 18 '19 at 11:34
0

I think that your best option is to deserialize your JSON to a C# object like explained in Ehsan's answer.

However, if you don't want to create a C# object and just use the raw info, I suggest you to use a good json library like Json.NET, which allows you to query your JSON easily:

internal static void GetInfoFromJson()
{
    string json = @"{
                    ""SchoolName"": ""ThisIsTheSchoolName"",
                      ""Student"": [
                        {
                          ""Id"": ""s001"",
                          ""Name"": ""ABC""
                        },
                        {
                          ""Id"": ""s002"",
                          ""Name"": ""CDE""
                        },
                        {
                          ""Id"": ""s003"",
                          ""Name"": ""EFG""
                        },
                        {
                          ""Id"": ""s004"",
                          ""Name"": ""GHI""
                        },
                        {
                          ""Id"": ""s005"",
                          ""Name"": ""IJK""
                        }
                    ]
                    }";
    JToken data = JObject.Parse(json);
    var schoolName = data["SchoolName"];
    foreach (JToken student in data["Student"])
    {
        string id = student["Id"].ToString();
        string name = student["Name"].ToString();
    }
}
Tao Gómez Gil
  • 2,228
  • 20
  • 36