我在C#工作,在那里我创建了一个小项目。在项目中我正在解析一个json文件。我只是想问我可以解析或使用json文件,如......
JSON文件
{
"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#代码
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"]);
}
当我解析JSON文件时,我没有得到位置数的值。那么你能帮我知道如何获取n umber of location的值。
答案 0 :(得分:2)
你应该使用JArray来解析一个json数组,代码看起来像这样:
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);
}
}
如果您只想使用此位置的数量:
var res = JObject.Parse(text)["Nodes"];
Console.WriteLine(res[0]["Number of Location"]);