当前位置:   article > 正文

jsonpath - 使用 JSONPath 解析 JSON 完整内容详解_jsonpath =~

jsonpath =~

目录

1.操作符

2.函数

3.过滤器运算符

4.Java操作示例

5.阅读文档

何时返回

谓词

6.调整配置

7.Java操作示例源码

json

Java

 

输出

示例2

Java

输出

过滤器示例

Java

输出


JsonPath是一种简单的方法来提取给定JSON文档的部分内容。 JsonPath有许多编程语言,如Javascript,Python和PHP,Java。

JsonPath提供的json解析非常强大,它提供了类似正则表达式的语法,基本上可以满足所有你想要获得的json内容。下面我把官网介绍的每个表达式用代码实现,可以更直观的知道该怎么用它。


JsonPath可在Central Maven存储库中找到。 Maven用户将其添加到您的POM。

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.2.0</version>
</dependency>

如果您需要帮助,请在Stack Overflow中提问。 标记问题'jsonpath'和'java'。

JsonPath表达式总是以与XPath表达式结合使用XML文档相同的方式引用JSON结构。

JsonPath中的“根成员对象”始终称为$,无论是对象还是数组。

JsonPath表达式可以使用点表示法

$.store.book [0].title

或括号表示法

$['store']['book'][0]['title']

1.操作符

操作说明
$查询根元素。这将启动所有路径表达式。
@当前节点由过滤谓词处理。
*通配符,必要时可用任何地方的名称或数字。
..深层扫描。 必要时在任何地方可以使用名称。
.<name>点,表示子节点
['<name>' (, '<name>')]括号表示子项
[<number> (, <number>)]数组索引或索引
[start:end]数组切片操作
[?(<expression>)]过滤表达式。 表达式必须求值为一个布尔值。

2.函数

函数可以在路径的尾部调用,函数的输出是路径表达式的输出,该函数的输出是由函数本身所决定的。

函数描述输出
min()提供数字数组的最小值Double
max()提供数字数组的最大值Double
avg()提供数字数组的平均值Double
stddev()提供数字数组的标准偏差值Double
length()提供数组的长度Integer

3.过滤器运算符

过滤器是用于筛选数组的逻辑表达式。一个典型的过滤器将是[?(@.age > 18)],其中@表示正在处理的当前项目。 可以使用逻辑运算符&&和||创建更复杂的过滤器。 字符串文字必须用单引号或双引号括起来([?(@.color == 'blue')] 或者 [?(@.color == "blue")]).

操作符描述
==left等于right(注意1不等于'1')
!=不等于
<小于
<=小于等于
>大于
>=大于等于
=~匹配正则表达式[?(@.name =~ /foo.*?/i)]
in左边存在于右边 [?(@.size in ['S', 'M'])]
nin左边不存在于右边
size(数组或字符串)长度
empty(数组或字符串)为空

4.Java操作示例

JSON

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}
JsonPath (点击链接测试)结果
$.store.book[*].author获取json中store下book下的所有author值
$..author获取所有json中所有author的值
$.store.*所有的东西,书籍和自行车
$.store..price获取json中store下所有price的值
$..book[2]获取json中book数组的第3个值
$..book[-2]倒数的第二本书
$..book[0,1]前两本书
$..book[:2]从索引0(包括)到索引2(排除)的所有图书
$..book[1:2]从索引1(包括)到索引2(排除)的所有图书
$..book[-2:]获取json中book数组的最后两个值
$..book[2:]获取json中book数组的第3个到最后一个的区间值
$..book[?(@.isbn)]获取json中book数组中包含isbn的所有值
$.store.book[?(@.price < 10)]获取json中book数组中price<10的所有值
$..book[?(@.price <= $['expensive'])]获取json中book数组中price<=expensive的所有值
$..book[?(@.author =~ /.*REES/i)]获取json中book数组中的作者以REES结尾的所有值(REES不区分大小写)
$..*逐层列出json中的所有值,层级由外到内
$..book.length()获取json中book数组的长度

5.阅读文档

使用JsonPath的最简单的最直接的方法是通过静态读取API。

  1. String json = "...";
  2. List<String> authors = JsonPath.read(json, "$.store.book[*].author");

如果你只想读取一次,那么上面的代码就可以了

如果你还想读取其他路径,现在上面不是很好的方法,因为他每次获取都需要再解析整个文档。所以,我们可以先解析整个文档,再选择调用路径。

  1. String json = "...";
  2. Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
  3. String author0 = JsonPath.read(document, "$.store.book[0].author");
  4. String author1 = JsonPath.read(document, "$.store.book[1].author");

JsonPath还提供流畅的API。 这也是最灵活的一个。

  1. String json = "...";
  2. ReadContext ctx = JsonPath.parse(json);
  3. List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");
  4. List<Map<String, Object>> expensiveBooks = JsonPath
  5. .using(configuration)
  6. .parse(json)
  7. .read("$.store.book[?(@.price > 10)]", List.class);

 

何时返回

当在java中使用JsonPath时,重要的是要知道你在结果中期望什么类型。 JsonPath将自动尝试将结果转换为调用者预期的类型。

  1. // 抛出 java.lang.ClassCastException 异常
  2. List<String> list = JsonPath.parse(json).read("$.store.book[0].author")
  3. // 正常
  4. String author = JsonPath.parse(json).read("$.store.book[0].author")

当评估路径时,你需要理解路径确定的概念。路径是不确定的,它包含

  • .. :深层扫描操作

  • ?(<expression>) :表达式

  • [<number>, <number> (, <number>)] :多个数组索引

不确定的路径总是返回一个列表(由当前的JsonProvider表示)。

默认情况下,MappingProvider SPI提供了一个简单的对象映射器。 这允许您指定所需的返回类型,MappingProvider将尝试执行映射。 在下面的示例中,演示了Long和Date之间的映射。

  1. String json = "{\"date_as_long\" : 1411455611975}";
  2. Date date = JsonPath.parse(json).read("$['date_as_long']", Date.class);

如果您将JsonPath配置为使用JacksonMappingProvider或GsonMappingProvider,您甚至可以将JsonPath输出直接映射到POJO中。

Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class);

要获取完整的泛型类型信息,请使用TypeRef。

  1. TypeRef<List<String>> typeRef = new TypeRef<List<String>>(){};
  2. List<String> titles = JsonPath.parse(JSON_DOCUMENT).read("$.store.book[*].title", typeRef);

谓词

在JsonPath中创建过滤器谓词有三种不同的方法。

内联谓词

内联谓词是路径中定义的谓词。

List<Map<String, Object>> books =  JsonPath.parse(json).read("$.store.book[?(@.price < 10)]");

你可以使用 && 和 || 结合多个谓词 [?(@.price < 10 && @.category == 'fiction')] , [?(@.category == 'reference' || @.price > 10)].

你也可以使用!否定一个谓词 [?(!(@.price < 10 && @.category == 'fiction'))].

过滤谓词

谓词可以使用Filter API构建,如下所示:

​​​​​​​import static com.jayway.jsonpath.JsonPath.parse; import static com.jayway.jsonpath.Criteria.where; import static com.jayway.jsonpath.Filter.filter; ... ... Filter cheapFictionFilter = filter( where("category").is("fiction").and("price").lte(10D) ); List<Map<String, Object>> books = parse(json).read("$.store.book[?]", cheapFictionFilter);

注意占位符? 为路径中的过滤器。 当提供多个过滤器时,它们按照占位符数量与提供的过滤器数量相匹配的顺序应用。 您可以在一个过滤器操作[?,?]中指定多个谓词占位符,这两个谓词都必须匹配。

过滤器也可以与“OR”和“AND”

  1. Filter fooOrBar = filter(
  2. where("foo").exists(true)).or(where("bar").exists(true)
  3. );
  4. Filter fooAndBar = filter(
  5. where("foo").exists(true)).and(where("bar").exists(true)
  6. );

自定义

第三个选择是实现你自己的谓词

  1. Predicate booksWithISBN = new Predicate() {
  2. @Override
  3. public boolean apply(PredicateContext ctx) {
  4. return ctx.item(Map.class).containsKey("isbn");
  5. }
  6. };
  7. List<Map<String, Object>> books = reader.read("$.store.book[?].isbn", List.class, booksWithISBN);

Path vs Value

在Goessner实现中,JsonPath可以返回Path或Value。 值是默认值,上面所有示例返回。 如果你想让我们查询的元素的路径可以通过选项来实现。

  1. Configuration conf = Configuration.builder().options(Option.AS_PATH_LIST).build();
  2. List<String> pathList = using(conf).parse(json).read("$..author");
  3. assertThat(pathList).containsExactly(
  4. "$['store']['book'][0]['author']", "$['store']['book'][1]['author']",
  5. "$['store']['book'][2]['author']", "$['store']['book'][3]['author']");

6.调整配置

选项创建配置时,有几个可以改变默认行为的选项标志。

DEFAULT_PATH_LEAF_TO_NULL

此选项使JsonPath对于缺少的叶子返回null。 考虑下面的json

[
   {
      "name" : "john",
      "gender" : "male"
   },
   {
      "name" : "ben"
   }
]

 

Configuration conf = Configuration.defaultConfiguration();

// 正常
String gender0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
// 异常 PathNotFoundException thrown
String gender1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");

Configuration conf2 = conf.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);

// 正常
String gender0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
// 正常 (返回 null)
String gender1 = JsonPath.using(conf2).parse(json).read("$[1]['gender']");

ALWAYS_RETURN_LIST

此选项配置JsonPath返回列表

Configuration conf = Configuration.defaultConfiguration();

// 正常
List<String> genders0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
// 异常 PathNotFoundException thrown
List<String> genders1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");

SUPPRESS_EXCEPTIONS

该选项确保不会从路径评估传播异常。 遵循这些简单的规则:

  • 如果选项ALWAYS_RETURN_LIST存在,将返回一个空列表

  • 如果选项ALWAYS_RETURN_LIST不存在返回null

JsonProvider SPI

JsonPath is shipped with three different JsonProviders:

更改配置默认值只能在应用程序初始化时完成。 强烈不建议在运行时进行更改,尤其是在多线程应用程序中。

  1. Configuration.setDefaults(new Configuration.Defaults() {
  2. private final JsonProvider jsonProvider = new JacksonJsonProvider();
  3. private final MappingProvider mappingProvider = new JacksonMappingProvider();
  4. @Override
  5. public JsonProvider jsonProvider() {
  6. return jsonProvider;
  7. }
  8. @Override
  9. public MappingProvider mappingProvider() {
  10. return mappingProvider;
  11. }
  12. @Override
  13. public Set<Option> options() {
  14. return EnumSet.noneOf(Option.class);
  15. }
  16. });

请注意,JacksonJsonProvider需要com.fasterxml.jackson.core:jackson-databind:2.4.5,GsonJsonProvider需要在您的类路径上使用com.google.code.gson:gson:2.3.1。

Cache SPI

在JsonPath 2.1.0中,引入了一种新的Cache SPI。 这允许API消费者以适合其需求的方式配置路径缓存。 缓存必须在首次访问之前配置,或者抛出JsonPathException。 JsonPath附带两个缓存实现

  • com.jayway.jsonpath.spi.cache.LRUCache(默认,线程安全)

  • com.jayway.jsonpath.spi.cache.NOOPCache(无缓存)

如果要实现自己的缓存,API很简单。

  1. CacheProvider.setCache(new Cache() {
  2. //Not thread safe simple cache
  3. private Map<String, JsonPath> map = new HashMap<String, JsonPath>();
  4. @Override
  5. public JsonPath get(String key) {
  6. return map.get(key);
  7. }
  8. @Override
  9. public void put(String key, JsonPath jsonPath) {
  10. map.put(key, jsonPath);
  11. }
  12. });

7.Java操作示例源码

json

  1. {
  2. "store": {
  3. "book": [{
  4. "category": "reference",
  5. "author": "Nigel Rees",
  6. "title": "Sayings of the Century",
  7. "price": 8.95
  8. }, {
  9. "category": "fiction",
  10. "author": "Evelyn Waugh",
  11. "title": "Sword of Honour",
  12. "price": 12.99
  13. }, {
  14. "category": "fiction",
  15. "author": "Herman Melville",
  16. "title": "Moby Dick",
  17. "isbn": "0-553-21311-3",
  18. "price": 8.99
  19. }, {
  20. "category": "JavaWeb",
  21. "author": "X-rapido",
  22. "title": "Top-link",
  23. "isbn": "0-553-211231-3",
  24. "price": 32.68
  25. }, {
  26. "category": "fiction",
  27. "author": "J. R. R. Tolkien",
  28. "title": "The Lord of the Rings",
  29. "isbn": "0-395-19395-8",
  30. "price": 22.99
  31. }],
  32. "bicycle": {
  33. "color": "red",
  34. "price": 19.95
  35. }
  36. },
  37. "expensive": 10
  38. }

 

Java

  1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import com.jayway.jsonpath.JsonPath;
  6. public class TestJsonPath {
  7. public static void main(String[] args) {
  8. String sjson = readtxt();
  9. print("--------------------------------------getJsonValue--------------------------------------");
  10. getJsonValue(sjson);
  11. }
  12. private static String readtxt() {
  13. StringBuilder sb = new StringBuilder();
  14. try {
  15. FileReader fr = new FileReader("D:/books.txt");
  16. BufferedReader bfd = new BufferedReader(fr);
  17. String s = "";
  18. while((s=bfd.readLine())!=null) {
  19. sb.append(s);
  20. }
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. System.out.println(sb.toString());
  25. return sb.toString();
  26. }
  27. private static void getJsonValue(String json) {
  28. //The authors of all books:获取json中store下book下的所有author值
  29. List<String> authors1 = JsonPath.read(json, "$.store.book[*].author");
  30. //All authors:获取所有json中所有author的值
  31. List<String> authors2 = JsonPath.read(json, "$..author");
  32. //All things, both books and bicycles
  33. //authors3返回的是net.minidev.json.JSONArray:获取json中store下的所有value值,不包含key,如key有两个,book和bicycle
  34. List<Object> authors3 = JsonPath.read(json, "$.store.*");
  35. //The price of everything:获取json中store下所有price的值
  36. List<Object> authors4 = JsonPath.read(json, "$.store..price");
  37. //The third book:获取json中book数组的第3个值
  38. List<Object> authors5 = JsonPath.read(json, "$..book[2]");
  39. //The first two books:获取json中book数组的第1和第2两个个值
  40. List<Object> authors6 = JsonPath.read(json, "$..book[0,1]");
  41. //All books from index 0 (inclusive) until index 2 (exclusive):获取json中book数组的前两个区间值
  42. List<Object> authors7 = JsonPath.read(json, "$..book[:2]");
  43. //All books from index 1 (inclusive) until index 2 (exclusive):获取json中book数组的第2个值
  44. List<Object> authors8 = JsonPath.read(json, "$..book[1:2]");
  45. //Last two books:获取json中book数组的最后两个值
  46. List<Object> authors9 = JsonPath.read(json, "$..book[-2:]");
  47. //Book number two from tail:获取json中book数组的第3个到最后一个的区间值
  48. List<Object> authors10 = JsonPath.read(json, "$..book[2:]");
  49. //All books with an ISBN number:获取json中book数组中包含isbn的所有值
  50. List<Object> authors11 = JsonPath.read(json, "$..book[?(@.isbn)]");
  51. //All books in store cheaper than 10:获取json中book数组中price<10的所有值
  52. List<Object> authors12 = JsonPath.read(json, "$.store.book[?(@.price < 10)]");
  53. //All books in store that are not "expensive":获取json中book数组中price<=expensive的所有值
  54. List<Object> authors13 = JsonPath.read(json, "$..book[?(@.price <= $['expensive'])]");
  55. //All books matching regex (ignore case):获取json中book数组中的作者以REES结尾的所有值(REES不区分大小写)
  56. List<Object> authors14 = JsonPath.read(json, "$..book[?(@.author =~ /.*REES/i)]");
  57. //Give me every thing:逐层列出json中的所有值,层级由外到内
  58. List<Object> authors15 = JsonPath.read(json, "$..*");
  59. //The number of books:获取json中book数组的长度
  60. List<Object> authors16 = JsonPath.read(json, "$..book.length()");
  61. print("**********authors1**********");
  62. print(authors1);
  63. print("**********authors2**********");
  64. print(authors2);
  65. print("**********authors3**********");
  66. printOb(authors3);
  67. print("**********authors4**********");
  68. printOb(authors4);
  69. print("**********authors5**********");
  70. printOb(authors5);
  71. print("**********authors6**********");
  72. printOb(authors6);
  73. print("**********authors7**********");
  74. printOb(authors7);
  75. print("**********authors8**********");
  76. printOb(authors8);
  77. print("**********authors9**********");
  78. printOb(authors9);
  79. print("**********authors10**********");
  80. printOb(authors10);
  81. print("**********authors11**********");
  82. printOb(authors11);
  83. print("**********authors12**********");
  84. printOb(authors12);
  85. print("**********authors13**********");
  86. printOb(authors13);
  87. print("**********authors14**********");
  88. printOb(authors14);
  89. print("**********authors15**********");
  90. printOb(authors15);
  91. print("**********authors16**********");
  92. printOb(authors16);
  93. }
  94. private static void print(List<String> list) {
  95. for(Iterator<String> it = list.iterator();it.hasNext();) {
  96. System.out.println(it.next());
  97. }
  98. }
  99. private static void printOb(List<Object> list) {
  100. for(Iterator<Object> it = list.iterator();it.hasNext();) {
  101. System.out.println(it.next());
  102. }
  103. }
  104. private static void print(String s) {
  105. System.out.println("\n"+s);
  106. }
  107. }

 

输出

  1. {
  2. "store": {
  3. "book": [{
  4. "category": "reference",
  5. "author": "Nigel Rees",
  6. "title": "Sayings of the Century",
  7. "price": 8.95
  8. }, {
  9. "category": "fiction",
  10. "author": "Evelyn Waugh",
  11. "title": "Sword of Honour",
  12. "price": 12.99
  13. }, {
  14. "category": "fiction",
  15. "author": "Herman Melville",
  16. "title": "Moby Dick",
  17. "isbn": "0-553-21311-3",
  18. "price": 8.99
  19. }, {
  20. "category": "JavaWeb",
  21. "author": "X-rapido",
  22. "title": "Top-link",
  23. "isbn": "0-553-211231-3",
  24. "price": 32.68
  25. }, {
  26. "category": "fiction",
  27. "author": "J. R. R. Tolkien",
  28. "title": "The Lord of the Rings",
  29. "isbn": "0-395-19395-8",
  30. "price": 22.99
  31. }],
  32. "bicycle": {
  33. "color": "red",
  34. "price": 19.95
  35. }
  36. },
  37. "expensive": 10
  38. }
  1. --------------------------------------getJsonValue--------------------------------------
  2. SLF4J: Class path contains multiple SLF4J bindings.
  3. SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/apache/logging/log4j/log4j-slf4j-impl/2.0.2/log4j-slf4j-impl-2.0.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
  4. SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/slf4j/slf4j-log4j12/1.7.10/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
  5. SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
  6. SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
  7. ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
  8. **********authors1**********
  9. Nigel Rees
  10. Evelyn Waugh
  11. Herman Melville
  12. X-rapido
  13. J. R. R. Tolkien
  14. **********authors2**********
  15. Nigel Rees
  16. Evelyn Waugh
  17. Herman Melville
  18. X-rapido
  19. J. R. R. Tolkien
  20. **********authors3**********
  21. [{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
  22. {color=red, price=19.95}
  23. **********authors4**********
  24. 8.95
  25. 12.99
  26. 8.99
  27. 32.68
  28. 22.99
  29. 19.95
  30. **********authors5**********
  31. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  32. **********authors6**********
  33. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  34. {category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}
  35. **********authors7**********
  36. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  37. {category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}
  38. **********authors8**********
  39. {category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}
  40. **********authors9**********
  41. {category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
  42. {category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
  43. **********authors10**********
  44. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  45. {category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
  46. {category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
  47. **********authors11**********
  48. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  49. {category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
  50. {category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
  51. **********authors12**********
  52. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  53. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  54. **********authors13**********
  55. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  56. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  57. **********authors14**********
  58. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  59. **********authors15**********
  60. {book=[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}], bicycle={color=red, price=19.95}}
  61. 10
  62. [{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
  63. {color=red, price=19.95}
  64. {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
  65. {category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}
  66. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  67. {category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
  68. {category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
  69. reference
  70. Nigel Rees
  71. Sayings of the Century
  72. 8.95
  73. fiction
  74. Evelyn Waugh
  75. Sword of Honour
  76. 12.99
  77. fiction
  78. Herman Melville
  79. Moby Dick
  80. 0-553-21311-3
  81. 8.99
  82. JavaWeb
  83. X-rapido
  84. Top-link
  85. 0-553-211231-3
  86. 32.68
  87. fiction
  88. J. R. R. Tolkien
  89. The Lord of the Rings
  90. 0-395-19395-8
  91. 22.99
  92. red
  93. 19.95
  94. **********authors16**********
  95. 5

 

示例2

Java

  1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import java.util.Map;
  6. import com.jayway.jsonpath.Configuration;
  7. import com.jayway.jsonpath.JsonPath;
  8. import com.jayway.jsonpath.ReadContext;
  9. public class TestJsonPath3 {
  10. public static void main(String[] args) {
  11. String sjson = readtxt();
  12. print("-----------------------getJsonValue0-----------------------");
  13. getJsonValue0(sjson);
  14. print("-----------------------getJsonValue1-----------------------");
  15. getJsonValue1(sjson);
  16. print("-----------------------getJsonValue2-----------------------");
  17. getJsonValue2(sjson);
  18. print("-----------------------getJsonValue3-----------------------");
  19. getJsonValue3(sjson);
  20. print("-----------------------getJsonValue4-----------------------");
  21. getJsonValue4(sjson);
  22. }
  23. private static String readtxt() {
  24. StringBuilder sb = new StringBuilder();
  25. try {
  26. FileReader fr = new FileReader("D:/books.txt");
  27. BufferedReader bfd = new BufferedReader(fr);
  28. String s = "";
  29. while((s=bfd.readLine())!=null) {
  30. sb.append(s);
  31. }
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. System.out.println(sb.toString());
  36. return sb.toString();
  37. }
  38. /**
  39. * 读取json的一种写法,得到匹配表达式的所有值
  40. * */
  41. private static void getJsonValue0(String json) {
  42. List<String> authors = JsonPath.read(json, "$.store.book[*].author");
  43. print(authors);
  44. }
  45. /**
  46. * 读取JSON得到某个具体值(推荐使用这种方法,一次解析多次调用)
  47. * */
  48. private static void getJsonValue1(String json) {
  49. Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
  50. String author0 = JsonPath.read(document, "$.store.book[0].author");
  51. String author1 = JsonPath.read(document, "$.store.book[1].author");
  52. print(author0);
  53. print(author1);
  54. }
  55. /**
  56. * 读取json的一种写法
  57. * */
  58. private static void getJsonValue2(String json) {
  59. ReadContext ctx = JsonPath.parse(json);
  60. // 获取json中book数组中包含isbn的作者
  61. List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");
  62. // 获取json中book数组中价格大于10的对象
  63. List<Map<String, Object>> expensiveBooks = JsonPath
  64. .using(Configuration.defaultConfiguration())
  65. .parse(json)
  66. .read("$.store.book[?(@.price > 10)]", List.class);
  67. print(authorsOfBooksWithISBN);
  68. print("********Map********");
  69. printListMap(expensiveBooks);
  70. }
  71. /**
  72. * 读取JSON得到的值是一个String,所以不能用List存储
  73. * */
  74. private static void getJsonValue3(String json) {
  75. //Will throw an java.lang.ClassCastException
  76. //List<String> list = JsonPath.parse(json).read("$.store.book[0].author");
  77. //由于会抛异常,暂时注释上面一行,要用的话,应使用下面的格式
  78. String author = JsonPath.parse(json).read("$.store.book[0].author");
  79. print(author);
  80. }
  81. /**
  82. * 读取json的一种写法,支持逻辑表达式,&&和||
  83. */
  84. private static void getJsonValue4(String json) {
  85. List<Map<String, Object>> books1 = JsonPath.parse(json).read("$.store.book[?(@.price < 10 && @.category == 'fiction')]");
  86. List<Map<String, Object>> books2 = JsonPath.parse(json).read("$.store.book[?(@.category == 'reference' || @.price > 10)]");
  87. print("********books1********");
  88. printListMap(books1);
  89. print("********books2********");
  90. printListMap(books2);
  91. }
  92. private static void print(List<String> list) {
  93. for(Iterator<String> it = list.iterator();it.hasNext();) {
  94. System.out.println(it.next());
  95. }
  96. }
  97. private static void printListMap(List<Map<String, Object>> list) {
  98. for(Iterator<Map<String, Object>> it = list.iterator();it.hasNext();) {
  99. Map<String, Object> map = it.next();
  100. for(Iterator iterator =map.entrySet().iterator();iterator.hasNext();) {
  101. System.out.println(iterator.next());
  102. }
  103. }
  104. }
  105. private static void print(String s) {
  106. System.out.println("\n"+s);
  107. }
  108. }

输出

  1. {"store":{"book":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"bicycle":{"color":"red","price":19.95}},"expensive":10}
  2. -----------------------getJsonValue0-----------------------
  3. SLF4J: Class path contains multiple SLF4J bindings.
  4. SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/apache/logging/log4j/log4j-slf4j-impl/2.0.2/log4j-slf4j-impl-2.0.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
  5. SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/slf4j/slf4j-log4j12/1.7.10/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
  6. SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
  7. SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
  8. ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
  9. Nigel Rees
  10. Evelyn Waugh
  11. Herman Melville
  12. X-rapido
  13. J. R. R. Tolkien
  14. -----------------------getJsonValue1-----------------------
  15. Nigel Rees
  16. Evelyn Waugh
  17. -----------------------getJsonValue2-----------------------
  18. Herman Melville
  19. X-rapido
  20. J. R. R. Tolkien
  21. ********Map********
  22. category=fiction
  23. author=Evelyn Waugh
  24. title=Sword of Honour
  25. price=12.99
  26. category=JavaWeb
  27. author=X-rapido
  28. title=Top-link
  29. isbn=0-553-211231-3
  30. price=32.68
  31. category=fiction
  32. author=J. R. R. Tolkien
  33. title=The Lord of the Rings
  34. isbn=0-395-19395-8
  35. price=22.99
  36. -----------------------getJsonValue3-----------------------
  37. Nigel Rees
  38. -----------------------getJsonValue4-----------------------
  39. ********books1********
  40. category=fiction
  41. author=Herman Melville
  42. title=Moby Dick
  43. isbn=0-553-21311-3
  44. price=8.99
  45. ********books2********
  46. category=reference
  47. author=Nigel Rees
  48. title=Sayings of the Century
  49. price=8.95
  50. category=fiction
  51. author=Evelyn Waugh
  52. title=Sword of Honour
  53. price=12.99
  54. category=JavaWeb
  55. author=X-rapido
  56. title=Top-link
  57. isbn=0-553-211231-3
  58. price=32.68
  59. category=fiction
  60. author=J. R. R. Tolkien
  61. title=The Lord of the Rings
  62. isbn=0-395-19395-8
  63. price=22.99

 

过滤器示例

Java

  1. public static void main(String[] args) {
  2. String json = readtxt();
  3. Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
  4. // 过滤器链(查找包含isbn并category中有fiction或JavaWeb的值)
  5. Filter filter = Filter.filter(Criteria.where("isbn").exists(true).and("category").in("fiction", "JavaWeb"));
  6. List<Object> books = JsonPath.read(document, "$.store.book[?]", filter);
  7. printOb(books);
  8. System.out.println("\n----------------------------------------------\n");
  9. // 自定义过滤器
  10. Filter mapFilter = new Filter() {
  11. @Override
  12. public boolean apply(PredicateContext context) {
  13. Map<String, Object> map = context.item(Map.class);
  14. if (map.containsKey("isbn")) {
  15. return true;
  16. }
  17. return false;
  18. }
  19. };
  20. List<Object> books2 = JsonPath.read(document, "$.store.book[?]", mapFilter);
  21. printOb(books2);
  22. }

输出

  1. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  2. {category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
  3. {category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
  4. ----------------------------------------------
  5. {category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
  6. {category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
  7. {category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/991114
推荐阅读
相关标签
  

闽ICP备14008679号