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

Get each item from a list and compare it with a different one

I have a piece of code, which should take a item name from a JSON, then compare it against a price list. If the name is there then it will find the price and add it to a listview. The problem with that is if I tried to add a foreach loop there, then it throws me a error. Here's my code:

JObject tokenJson2 = JObject.Parse(json2);
foreach (var data2 in tokenJson2["response"])
var item = data2.ToArray()
.SingleOrDefault(x => ((JProperty)x).Name == name.ToString()) as JProperty;

if (item != null)

Here is the error I get:

Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type

Here is the tokenJson2 data: Link

Answer Source

According to your (kind of unusual) JSON structure, "response" is a JProperty with value being JObject, containing multiple JProperty elements with the name being the JProperty.Name and value being JObject with "price" and "quantity" properties.

It can be iterated this way:

var response = (JObject)tokenJson2.Property("response").Value;
foreach (var item in response.Properties())
    var name = item.Name;
    var data = (JObject)item.Value;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download