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.
2
Answers
To get the value corresponding to a specific name, you can loop through the array and check each object’s name property until you find the one you’re looking for. Here’s an example implementation:
This implementation uses a loop to iterate through each object in the middle array and checks if the name property matches the one we’re looking for. If it does, it retrieves the value property and breaks out of the loop. If it doesn’t find a matching object, it outputs a message indicating that no object was found.
Note that this implementation assumes that there is only one object with the specified name in the middle array. If there could be multiple objects with the same name, you may need to modify the implementation to handle that scenario.
I would rather to use Linq