我需要在 C# (winforms) 中读取 json 文件,但我在这样做时遇到了一些麻烦。
这是文件的简单内容: 它包含 2 条路线,每条路线都有一条腿和一个或多个台阶
{
"routes" : [
{
"legs" : [
{
"distance" : {
"text" : "246 km",
"value" : 246047
},
"steps" : [
{
"distance" : {
"text" : "2.4 km",
"value" : 2383
},
},
{
"distance" : {
"text" : "3.7 km",
"value" : 3697
},
},
],
}
],
},
{
"legs" : [
{
"distance" : {
"text" : "280 km",
"value" : 280048
},
"steps" : [
{
"distance" : {
"text" : "2.4 km",
"value" : 2383
},
},
{
"distance" : {
"text" : "6.9 km",
"value" : 3697
},
},
],
}
],
}
],
}
我需要做的是:
1.找到最短路线(这是我设法做到的)
2.循环遍历最短路径的步骤,这个我不知道怎么办
我寻找最短路线的代码是这样的:
JObject o = JObject.Parse(content);
JToken token = null;
decimal distance = 0;
decimal shortest = 0;
JToken routes = o.SelectToken("routes");
foreach (JToken tempToken in routes.Children())
{
distance = (decimal)tempToken.SelectToken("legs[0].distance.value") / 1000;
if (distance < shortest || shortest == 0)
{
shortest = distance;
token = tempToken.SelectToken("legs[0]").First;
}
}
在此代码之后,shortest 包含 246047,因此这是有效的。
但变量 token 包含该文件的所有路径,而不仅仅是最短路线的第一条路径。
我希望最终得到一个仅包含最短路线的步骤的变量 token ,这样我就可以循环遍历这个 token 。
也许我完全错了,它只是不起作用?
如何循环执行最短路线的步骤?
编辑: 我尝试了另一种方法,但结果相同。 这是我的第二种方法:
int index = 0;
foreach (JToken tempToken in routes.Children())
{
distance = (decimal)tempToken.SelectToken("legs[0].distance.value") / 1000;
if (distance < shortest || shortest == 0)
{
shortest = distance;
token = o.SelectToken("routes[" + index.ToString() + "].legs[0]");
}
index++;
}
此后,变量 token 仍然包含所有路线的所有支路。
最佳答案
试试这个。它会让你循环遍历最短腿的步骤
foreach (JToken tempToken in routes.Children())
{
distance = (decimal)tempToken.SelectToken("legs[0].distance.value") / 1000;
if (distance < shortest || shortest == 0)
{
shortest = distance;
IEnumerable<JToken> steps = tempToken["legs"].Children()["steps"].Children();
foreach (JToken step in steps)
{
var thisStep = step;
}
}
}
关于c# - 如何从 json 对象循环遍历某个 token?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35868505/