How to parse JSON file with different node
I am working in C # where I created one small project. In a project, I am parsing one json file. I just want to ask if I can parse or use a 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 Number of Locations value when I parse the JSON file. So can you help how can I get the n umber value of the location. ...
+3
source to share
1 answer
Well, you have to use JArray to parse the json array, the code will 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 only want the number of places to use this:
var res = JObject.Parse(text)["Nodes"];
Console.WriteLine(res[0]["Number of Location"]);
+2
source to share