【问题标题】:Using LINQ in JArray在 JArray 中使用 LINQ
【发布时间】:2021-06-01 09:30:14
【问题描述】:

我有一个 JSON

{
  "departments": [
    {
      "2": {"city": "Petersburg", "employees": "1200"}
    },
    {
      "1": {"city": "Ekaterinburg", "employees": "4000"}
    }
  ]
}

如果我知道使用 LINQ 或其他方法的 ID,我如何获得城市的价值?

我试过了

var id = 2;
json["departments"].Single(x=>x.Name==id.ToString())["city"];

但它不起作用,我得到一个编译错误:

'JToken' does not contain a definition for 'Name' and no accessible extension method 'Name' accepting a first argument of type 'JToken' could be found (are you missing a using directive or an assembly reference?)

演示小提琴here.

【问题讨论】:

    标签: c# json linq json.net


    【解决方案1】:

    您的 LINQ 查询可以按如下方式实现:

    var id = "2";
    var city = (string)json["departments"]
        .Where(o => o[id] != null) // From the departments array, select the object where the required id property exists
        .Select(o => o[id]["city"]).SingleOrDefault(); // An extract the value of "city" from the nested object.
    

    或者,等效地:

    var id = "2";
    var city = (string)json["departments"]
        .SelectMany(i => i) // Use SelectMany() to project the properties of the array items to a flat enumerable 
        .Cast<JProperty>()  // Cast them to JProperty
        .Where(p => p.Name == id) // Now you can use Name
        .Select(p => p.Value["city"])
        .SingleOrDefault();
    

    或者,您也可以为此使用SelectToken()

    var id = "2";
    var path = $"departments[*].{id}.city"; // departments[*].2.city
    var city = (string)json.SelectToken(path);
    

    SelectToken() 支持JSONPath syntax[*] 是 JSONPath 通配符,表示应该搜索所有数组项。

    演示小提琴here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 2014-08-11
      • 2022-07-19
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多