簡體   English   中英

如何使用linq從json獲取數據?

[英]How I get data from json with linq?

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

我想在數組“產品”包含“ 321”的地方獲取“標簽”。 我該怎么做? 我用庫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; }

}

然后反序列化而不是對象:

 var deserialized = serializer.Deserialize<MyObj>(str);
 var result =  deserialized.Where(r => r.products.Contains("321")).ToList();

您需要使用JSON.NET之類的庫。 在這種情況下,您可以編寫如下內容

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; }
}

為此,您可以使用任何JSON庫。 例如JSON.NET

LINQ to JSON示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM