Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用linq从json获取数据?_C#_Json_Linq - Fatal编程技术网

C# 如何使用linq从json获取数据?

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

我想获取数组“products”包含“321”的“label”。我怎样才能做到这一点?我使用了json.net库

[
  {
    "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; }
}