rajeev patidar
rajeev patidar

Reputation: 85

How to parse JSON file with different node

i am working in C#,where I created one small project.In the project I am parsing one json file.I just want to ask that can I parse or use the json file like.....

JSON File

{
"Nodes": [
      {
        "Number of Location":"4",
      },
      {
        "longitude": "22.3 ",
        "latitude": "45.3",
        "Demand": "5"
      },
      {
        "longitude": "26.3 ",
        "latitude": "46.3",
        "Demand": "6"
      },
      {
        "longitude": "35.1 ",
        "latitude": "48.2",
        "Demand": "2"
      }
]
}

C# code

 string path = null;
 Console.WriteLine("enter the path where order matrix is loacated");
 path = Console.ReadLine();
 System.IO.StreamReader myFile = new System.IO.StreamReader(path);
 string myString = myFile.ReadToEnd();
 JObject o = JObject.Parse(myString);
 Console.WriteLine(o["Nodes"][0]["Number of Location"]);
 for (int i = 0; i < 5; i++)
 {
     Console.WriteLine(o["Nodes"][i+1]["longitude"]);
     Console.WriteLine(o["Nodes"][i+1]["latitude"]);
     Console.WriteLine(o["Nodes"][i+1]["Demand"]);
 }   

I am not getting the value of Number of location when i am parsing the JSON file.so can you help that how can I fetch the value of number of location..

Upvotes: 3

Views: 343

Answers (1)

Coder1409
Coder1409

Reputation: 498

Well you should be using JArray to parse a json Array , the code would look like this :

        var res = JObject.Parse(text)["Nodes"];
        foreach (var o in res.Children<JObject>())
        {
            foreach (var property in o.Properties())
            {
                Console.WriteLine(property.Name + " " + property.Value);
            }
        }

if you want just the number of location use this:

        var res = JObject.Parse(text)["Nodes"];
        Console.WriteLine(res[0]["Number of Location"]);

Upvotes: 2

Related Questions