[
{
"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"
]
}
]
我想获得数组"products"中包含"321"的" label "。我怎么能做到呢?我使用了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));
但我得到"无法访问Newtonsoft.Json.Linq.JValue的子值。"
所以你应该先定义这个类:
class MyObj {
public string id { get; set; }
public string[] products { get; set; }
public string label { get; set; }
}
反序列化,而不是object:
var deserialized = serializer.Deserialize<MyObj>(str);
var result = deserialized.Where(r => r.products.Contains("321")).ToList();
为此,您可以使用任何JSON库。例如JSON。净
这个LINQ到JSON的示例
您需要使用JSON.NET之类的库。在这种情况下,你可以这样写
string json = <your json string>;
var deserializedProduct = JsonConvert.DeserializeObject<List<Product>>(json).Where(p => p.products.Contains("321")).ToList();
其中Product为
public class Product
{
public string id { get; set; }
public string[] products { get; set; }
public string label { get; set; }
}