[
{
"id": "133",
"label": "S/M",
"price": "0",
"oldPrice": "0",
"products": [
"318",
"321",
"324",
"327"
]
},
{
"id": "132",
"label": "L/XL",
"price": "0",
"oldPrice": "0",
"products": [
"319",
"322",
"325",
"328"
]
},
{
"id": "131",
"label": "XXL/XXXL",
"price": "0",
"oldPrice": "0",
"products": [
"320",
"323",
"326",
"329"
]
}
]
I want to get 'label' where array "products" contains "321". How i can make this? I used library json.net
i make linq expression
JArray ja = JArray("this json");
JValue id = JValue.Parse("328");
ja.Select(x => x["label"]).Where(x => x["products"].Contains(id));
But i get "Cannot access child value on Newtonsoft.Json.Linq.JValue."
user3436765user3436765
-
3Have you tried using a JSON deserializer such as JSON.NET?Tim Rogers– Tim Rogers2014年03月19日 09:13:32 +00:00Commented Mar 19, 2014 at 9:13
3 Answers 3
So you should define the class first:
class MyObj {
public string id { get; set; }
public string[] products { get; set; }
public string label { get; set; }
}
And deserialize that instead of object:
var deserialized = serializer.Deserialize<MyObj>(str);
var result = deserialized.Where(r => r.products.Contains("321")).ToList();
answered Mar 19, 2014 at 9:16
Sign up to request clarification or add additional context in comments.
1 Comment
Ilya Ivanov
serializer.Deserialize<MyObj>(str);
this won't work, OP has an array of itemsFor this you can use any JSON library. e.g. JSON.NET
This LINQ to JSON sample
answered Mar 19, 2014 at 9:19
1 Comment
user3436765
I used this library. But i cant make correct linq expression.
You need to use a library like JSON.NET. In this case you can write something like this
string json = <your json string>;
var deserializedProduct = JsonConvert.DeserializeObject<List<Product>>(json).Where(p => p.products.Contains("321")).ToList();
where Product is
public class Product
{
public string id { get; set; }
public string[] products { get; set; }
public string label { get; set; }
}
Comments
lang-cs