Json.Net:使用SelectToken让不知道的元素名称的价值呢? [英] Json.Net: Using SelectToken to get a value without knowing an element name?
问题描述
我有我需要得到令牌的价值,我已经使用SelectToken尝试一个简单的JSON文件,但问题是,元素的名称是动态的。这是我的JSON文件
I have a simple JSON file which i need to get the value of a token, i have tried using SelectToken but the problem is that the name of the elements are dynamic. Here is my JSON file
{
"name": "testdata",
"items": {
"myItemName": {
"located": true
}
}
}
我需要的位置(上图)的价值,如果你看到的元素名称myItemName,这是动态的,不是固定不变的。所以,我没有尝试使用SelectToken的点符号。
I need to get the value of "located" (above), If you see the element name "myItemName", this is dynamic and not fixed. So I did try using the dot notation of SelectToken.
我想出了类似的话,但没有奏效 - 问题是,[0]
I came up with something like so, but it didn't work - problem is the [0]
bool located = (bool)jsonObject.SelectToken("items.[0].located");
内的项目,可以有多于1动态元件,因此,例如,这是有效的。
Within Items, there can be more than 1 dynamic element, so for example, this is valid.
{
"name": "testdata",
"items": {
"myItemName": {
"located": true
},
"myOtherItemName": {
"located": true
}
}
}
所以看上面,你可以看到我有myItemName和myOtherItemName,我想使用的foreach somekind的取得每一个定位的值
So looking above, you can see I have "myItemName" and "myOtherItemName", I would like to get the values of "located" in each one using somekind of foreach
这是在所有可能的?使用SelectToken?
Is this at all possible ? Using SelectToken?
感谢
推荐答案
试试这个:
string json = @"
{
""name"": ""testdata"",
""items"": {
""myItemName"": {
""located"": true
},
""myOtherItemName"": {
""located"": true
}
}
}";
JObject jsonObject = JObject.Parse(json);
foreach (JProperty prop in jsonObject.SelectToken("items"))
{
string name = prop.Name;
bool value = (bool)prop.Value.SelectToken("located");
Console.WriteLine(name + " = " + value);
}
输出:
myItemName = True
myOtherItemName = True
这篇关于Json.Net:使用SelectToken让不知道的元素名称的价值呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!