在 JArray 中使用 LINQ
Using LINQ in JArray
我有一个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?)
演示 fiddle here.
您的 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通配符,表示搜索所有数组项。
演示 fiddle here.
我有一个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?)
演示 fiddle here.
您的 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通配符,表示搜索所有数组项。
演示 fiddle here.