原文:
操作Json 和 SelectTokens with JsonPath
JsonPath expression:
$ | the root object |
@ | the current object |
.. | recursive descent |
[] | 下标操作符 |
* | 通配符 |
?() | filter 条件 |
JToken. SelectToken
SelectToken是JToken上的一个方法,它采用字符串路径到child token。如果在路径的位置找不到child token.,则SelectToken将返回子child token或空引用。 该路径由以句点分隔的属性名称和数组索引组成,e.g. Manufacturers[0].Name.
-
JObject o = JObject.Parse(@"{
-
'Stores': [
-
'Lambton Quay',
-
'Willis Street'
-
],
-
'Manufacturers': [
-
{
-
'Name':
'Acme Co',
-
'Products': [
-
{
-
'Name':
'Anvil',
-
'Price':
50
-
}
-
]
-
},
-
{
-
'Name':
'Contoso',
-
'Products': [
-
{
-
'Name':
'Elbow Grease',
-
'Price':
99.95
-
},
-
{
-
'Name':
'Headlight Fluid',
-
'Price':
4
-
}
-
]
-
}
-
]
-
}
");
-
-
string name = (string)o.SelectToken("Manufacturers[
0].Name
");
-
// Acme Co
-
-
decimal productPrice = (decimal)o.SelectToken("Manufacturers[
0].Products[
0].Price
");
-
// 50
-
-
string productName = (string)o.SelectToken("Manufacturers[
1].Products[
0].Name
");
-
// Elbow Grease
JToken. SelectTokens with jsonPath
-
JObject o = JObject.Parse(@"{
-
'Stores': [
-
'Lambton Quay',
-
'Willis Street'
-
],
-
'Manufacturers': [
-
{
-
'Name':
'Acme Co',
-
'Products': [
-
{
-
'Name':
'Anvil',
-
'Price':
50
-
}
-
]
-
},
-
{
-
'Name':
'Contoso',
-
'Products': [
-
{
-
'Name':
'Elbow Grease',
-
'Price':
99.95
-
},
-
{
-
'Name':
'Headlight Fluid',
-
'Price':
4
-
}
-
]
-
}
-
]
-
}
");
-
-
// manufacturer with the name 'Acme Co'
-
JToken acme = o.SelectToken("$.Manufacturers[?(@.Name ==
'Acme Co')]
");
-
-
Console.WriteLine(acme);
-
// { "Name
": "Acme Co
", Products: [{ "Name
": "Anvil
", "Price
": 50 }] }
-
-
// name of all products priced 50 and above
-
IEnumerable<JToken> pricyProducts = o.SelectTokens("$..Products[?(@.Price >=
50)].Name
");
-
-
foreach (JToken item in pricyProducts)
-
{
-
Console.WriteLine(item);
-
}
-
// Anvil
-
// Elbow Grease
select Token with Linq
-
IList<string> storeNames = o.SelectToken(
"Stores").Select(
s => (string)s).ToList();
-
// Lambton Quay
-
// Willis Street
-
-
IList<string> firstProductNames = o[
"Manufacturers"].Select(
m => (string)m.SelectToken(
"Products[1].Name")).ToList();
-
// null
-
// Headlight Fluid
-
-
decimal totalPrice = o[
"Manufacturers"].Sum(
m => (decimal)m.SelectToken(
"Products[0].Price"));
-
// 149.95
我在项目中遇到的问题是:model下面有很多id,我需要根据传入的多个id去找:
来源:oschina
链接:https://my.oschina.net/u/4267086/blog/4279713