【问题标题】:How I get data from json with linq?如何使用 linq 从 json 获取数据?
【发布时间】:2014-03-19 09:10:30
【问题描述】:
[
  {
    "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”的“标签”。我怎样才能做到这一点?我使用了库 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 上的子值。”

【问题讨论】:

  • 您是否尝试过使用 JSON.NET 等 JSON 反序列化器?

标签: c# json linq


【解决方案1】:

所以你应该先定义类:

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();

【讨论】:

  • serializer.Deserialize&lt;MyObj&gt;(str); 这行不通,OP 有一系列项目
【解决方案2】:

为此,您可以使用任何 JSON 库。例如JSON.NET

LINQ to JSON 示例

【讨论】:

  • 我使用了这个库。但我无法做出正确的 linq 表达式。
【解决方案3】:

您需要使用像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; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2014-07-04
    • 2015-12-07
    相关资源
    最近更新 更多