C# 如何使用linq从json获取数据?
我想获取数组“products”包含“321”的“label”。我怎样才能做到这一点?我使用了json.net库C# 如何使用linq从json获取数据?,c#,json,linq,C#,Json,Linq,我想获取数组“products”包含“321”的“label”。我怎样才能做到这一点?我使用了json.net库 [ { "id": "133", "label": "S/M", "price": "0", "oldPrice": "0", "products": [ "318", "321", "324", "327" ] }, { "id": "132", "label
[
{
"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"
]
}
]
但是我得到“无法访问Newtonsoft.Json.Linq.JValue上的子值”。因此您应该首先定义类:
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));
并反序列化该对象,而不是对象:
class MyObj {
public string id { get; set; }
public string[] products { get; set; }
public string label { get; set; }
}
var deserialized=serializer.Deserialize(str);
var result=反序列化。其中(r=>r.products.Contains(“321”)).ToList();
您需要使用类似的库。
在这种情况下,你可以这样写
var deserialized = serializer.Deserialize<MyObj>(str);
var result = deserialized.Where(r => r.products.Contains("321")).ToList();
为此,您可以使用任何JSON库。e、 g
此示例您是否尝试过使用JSON反序列化程序,如JSON.NET?
serializer.Deserialize(str)代码>这不起作用,OP有一个项目数组我使用了这个库。但是我不能做出正确的linq表达。
string json = <your json string>;
var deserializedProduct = JsonConvert.DeserializeObject<List<Product>>(json).Where(p => p.products.Contains("321")).ToList();
public class Product
{
public string id { get; set; }
public string[] products { get; set; }
public string label { get; set; }
}