Search code examples
jsonjson.net

Get a Json Element from a changing array


ok so I have the following json response that contains an array of details.

{
 "top":{
   "middle":[
     {
         "name": "name1".
         "values":[
            {
                "value": 123
            }
         ]
     },
     {
         "name": "name2".
         "values":[
            {
                "value": 456
            }
         ]
     }
   ]
  }
}

I can get the data using:

JObject data = JObject.Parse(JSONDATA);
var Name1 = (string)data["top"]["middle"][0]["name"];
var Value1 = (float)data["top"]["middle"][0]["values"][0]["value"];

However, the order in which the items appear in the array are random. so I cant use the [0] and [1] to specify the first or second item.

i know i could still use this method and then work out if the name1 or name 2 was a match meaning i would know which value goes with each name. but it seems very long winded and i know there must be an easier way.

i have tried a few things like,

JToken mydata = data.SelectToken("$.top.middle[?(@.name == 'name1')]");

and i tried to get the index of the array based on the name value.

but i just cant get it right. any help would be greatly appreciated.


Solution

  • I would rather to use Linq

        var jObj = JObject.Parse(json);
    
        int value = GetValueByName("name1", jObj) // 123
    
    public int GetValueByName(string name, JObject jObj)
    {
       return jObj["top"]["middle"]
             .Where(x => (string)x["name"] == name)
             .Select(x => (int)x["values"][0]["value"])
             .FirstOrDefault();
    }