James Aniszt James Aniszt -4 years ago 98
C# Question

Compare root object value

I have a JSON list which has a two values

root object
name as a name and inside there a price. I have to compare the
root object name
with my variable called
marketName
and then grab the price there. What is the best way doing that? Here is my code at the moment:

foreach (JToken token2 in tokenJson2["response"])
{
var name2 = token2[0];

if(name2 == name)
{
// Do some fun here
}
}


The JSON data comes from here ( I couldn't post it here, because it's too big)

Answer Source

You can use Linq to iterate over the object and grab the one you want:

var item = tokenJson2["response"].ToArray()
             .SingleOrDefault(x => ((JProperty) x).Name == name) as JProperty;

if (item == null)
{
    throw new InvalidOperationException("Item not found.");
}

var price = item.Value["price"].ToObject<decimal>();

The confusing part here is that the endpoint is returning a property per item, instead of an array. Unfortunately you don't have any control over that :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download