Json.Net: Using SelectToken to get a value without knowing an element name?

后端 未结 1 1720
渐次进展
渐次进展 2020-12-21 12:00

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 J

1条回答
  •  一生所求
    2020-12-21 12:39

    Try this:

    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);
    }
    

    Output:

    myItemName = True
    myOtherItemName = True
    

    0 讨论(0)
提交回复
热议问题