JsonPath--使用

喜欢ヅ旅行 2024-02-19 17:38 119阅读 0赞

JsonPath:用来解析json,通过表达式获取方便获取json中的数据。

学习连接:https://github.com/json-path/JsonPath

参考连接:https://www.cnblogs.com/aoyihuashao/p/8665873.html

测试:

实体类:

  1. @Data
  2. public class MyFactory {
  3. private Store store;
  4. }
  5. @Data
  6. public class Store {
  7. private String storeName;
  8. private String stroeAddress;
  9. private String version;
  10. private List<Book> book;
  11. }
  12. @Data
  13. public class Book {
  14. private String category;
  15. private String author;
  16. private String title;
  17. private String isbn;
  18. private Integer price;
  19. }

获取json字符串:

  1. @Before
  2. public void getJson(){
  3. MyFactory myFactory=new MyFactory();
  4. Store store=new Store();
  5. List<Book> bookList=new ArrayList<>();
  6. Book book=new Book();
  7. book.setAuthor("Nigel Rees");
  8. book.setCategory("reference");
  9. book.setPrice(1);
  10. book.setTitle("Sayings of the Century");
  11. Book book1=new Book();
  12. book1.setAuthor("Herman Melville");
  13. book1.setCategory("fiction");
  14. book1.setIsbn("0-553-21311-3");
  15. book1.setPrice(2);
  16. book1.setTitle("Moby Dick");
  17. Book book2=new Book();
  18. book2.setAuthor("J. R. R. Tolkien");
  19. book2.setCategory("reference");
  20. book2.setPrice(3);
  21. book2.setIsbn("0-395-19395-8");
  22. book2.setTitle("The Lord of the Rings");
  23. bookList.add(book);
  24. bookList.add(book1);
  25. bookList.add(book2);
  26. store.setStoreName("书店");
  27. store.setStroeAddress("中国");
  28. store.setVersion("1.0");
  29. store.setBook(bookList);
  30. myFactory.setStore(store);
  31. Gson gson=new Gson();
  32. json= gson.toJson(myFactory);
  33. }

测试通配符:

  1. /**
  2. * $ 要查询的根元素。这将启动所有路径表达式。
  3. * @ 当前节点由过滤谓词处理。
  4. * * 通配符。可在任何名称或数字需要的地方使用。
  5. * .. 深层扫描。可在任何需要名称的地方使用。
  6. * .<name> 有点儿的孩子
  7. * ['<name>' (, '<name>')] 带支架的儿童或儿童
  8. * [<number> (, <number>)] 数组索引或索引
  9. * [start:end] 数组切片运算符
  10. * [?(<expression>)] 过滤表达式。表达式必须求值为布尔值。
  11. */
  12. @Test
  13. public void test1(){
  14. List<String> authorList = JsonPath.read(json, "$.store.book[*].author");
  15. System.out.println(authorList);
  16. System.out.println("-------------------------------------");
  17. Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
  18. String author0 = JsonPath.read(document, "$.store.book[0].author");
  19. String author1 = JsonPath.read(document, "$.store.book[1].author");
  20. System.out.println(author0);
  21. System.out.println(author1);
  22. }

测试返回类型:

  1. /**
  2. * 确定返回类型
  3. */
  4. @Test
  5. public void test2(){
  6. //解析json将其中数据放置到ReadContext
  7. ReadContext ctx = JsonPath.parse(json);
  8. //转成list
  9. List authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author", List.class);
  10. System.out.println(authorsOfBooksWithISBN);
  11. System.out.println("-------------------------------------");
  12. Configuration configuration=Configuration.defaultConfiguration();
  13. List<Map<String, Object>> expensiveBooks = using(configuration)
  14. .parse(json)
  15. .read("$.store.book[?(@.price > 10)]", List.class);
  16. System.out.println(expensiveBooks);
  17. System.out.println("-------------------------------------");
  18. //将json中的某个字段转成另一个类型
  19. String json1 = "{\"date_as_long\" : 1411455611975}";
  20. Date date = JsonPath.parse(json1).read("$['date_as_long']", Date.class);
  21. System.out.println(date);
  22. System.out.println("-------------------------------------");
  23. Book bookinfo = JsonPath.parse(json).read("$.store.book[0]", Book.class);
  24. System.out.println(bookinfo);
  25. }

测试过滤条件:

  1. /**
  2. * Predicates 过滤条件
  3. */
  4. @Test
  5. public void test3(){
  6. //list中放置map
  7. List<Map<String, Object>> books = JsonPath.parse(json) .read("$.store.book[?(@.price < 10)]");
  8. Filter cheapFictionFilter = Filter.filter(
  9. Criteria.where("category").is("fiction").and("price").lte(10D)
  10. );
  11. List<Map<String, Object>> bookmap =
  12. JsonPath.parse(json).read("$.store.book[?]", cheapFictionFilter);
  13. System.out.println(bookmap);
  14. System.out.println("-------------------------------------");
  15. // Filters can also be combined with 'OR' and 'AND'
  16. Filter fooOrBar = Filter.filter(
  17. Criteria.where("foo").exists(true)).or(where("bar").exists(true)
  18. );
  19. Filter fooAndBar = Filter.filter(
  20. Criteria.where("foo").exists(true)).and(where("bar").exists(true)
  21. );
  22. Predicate booksWithISBN = new Predicate() {
  23. @Override
  24. public boolean apply(PredicateContext ctx) {
  25. return ctx.item(Map.class).containsKey("isbn");
  26. }
  27. };
  28. List<Map<String, Object>> booksList =JsonPath.parse(json).read("$.store.book[?].isbn", List.class, booksWithISBN);
  29. Configuration conf = Configuration.builder().options(Option.AS_PATH_LIST).build();
  30. List<String> pathList = JsonPath.using(conf).parse(json).read("$..author");
  31. }

测试配置类Option:

  1. Option
  2. package com.jayway.jsonpath;
  3. public enum Option {
  4. /**
  5. * returns <code>null</code> for missing leaf.
  6. *
  7. * <pre>
  8. * [
  9. * {
  10. * "foo" : "foo1",
  11. * "bar" : "bar1"
  12. * }
  13. * {
  14. * "foo" : "foo2"
  15. * }
  16. * ]
  17. *</pre>
  18. *
  19. * the path :
  20. *
  21. * "$[*].bar"
  22. *
  23. * Without flag ["bar1"] is returned
  24. * With flag ["bar1", null] is returned
  25. *当检索不到时返回null对象,否则如果不配置这个,会直接抛出异常PathNotFoundException
  26. *
  27. */
  28. DEFAULT_PATH_LEAF_TO_NULL,
  29. /**
  30. * Makes this implementation more compliant to the Goessner spec. All results are returned as Lists.
  31. 总是返回list,即便是一个确定的非list类型,也会被包装成list。
  32. */
  33. ALWAYS_RETURN_LIST,
  34. /**
  35. * Returns a list of path strings representing the path of the evaluation hits
  36. 返回path
  37. */
  38. AS_PATH_LIST,
  39. /**
  40. * Suppress all exceptions when evaluating path.
  41. * <br/>
  42. * If an exception is thrown and the option {@link Option#ALWAYS_RETURN_LIST} an empty list is returned.
  43. * If an exception is thrown and the option {@link Option#ALWAYS_RETURN_LIST} is not present null is returned.
  44. 不抛出异常,需要判断如下:
  45. ALWAYS_RETURN_LIST开启,则返回空list
  46. ALWAYS_RETURN_LIST关闭,则返回null
  47. */
  48. SUPPRESS_EXCEPTIONS,
  49. /**
  50. * Configures JsonPath to require properties defined in path when an <bold>indefinite</bold> path is evaluated.
  51. *
  52. *
  53. * Given:
  54. *
  55. * <pre>
  56. * [
  57. * {
  58. * "a" : "a-val",
  59. * "b" : "b-val"
  60. * },
  61. * {
  62. * "a" : "a-val",
  63. * }
  64. * ]
  65. * </pre>
  66. *
  67. * evaluating the path "$[*].b"
  68. *
  69. * If REQUIRE_PROPERTIES option is present PathNotFoundException is thrown.
  70. * If REQUIRE_PROPERTIES option is not present ["b-val"] is returned.
  71. 如果设置,则不允许使用通配符,比如$[*].b,会抛出PathNotFoundException异常
  72. */
  73. REQUIRE_PROPERTIES
  74. }

测试:

  1. /**
  2. * Option
  3. * [
  4. * {
  5. * "name" : "john",
  6. * "gender" : "male"
  7. * },
  8. * {
  9. * "name" : "ben"
  10. * }
  11. * ]
  12. *
  13. * Option的使用规则
  14. */
  15. @Test
  16. public void test4(){
  17. Configuration configuration1 = Configuration.defaultConfiguration();
  18. // //Works fine 报错
  19. // String gender0 = using(configuration1).parse(json).read("$[0]['gender']");
  20. // //PathNotFoundException thrown
  21. // String gender1 = using(configuration1).parse(json).read("$[1]['gender']");
  22. //
  23. // System.out.println(gender0);
  24. // System.out.println(gender1);
  25. //
  26. // System.out.println("------------------------------------");
  27. //DEFAULT_PATH_LEAF_TO_NULL:当检索不到时返回null对象,否则如果不配置这个,会直接抛出异常PathNotFoundException
  28. //ALWAYS_RETURN_LIST 总是返回list,即便是一个确定的非list类型,也会被包装成list。
  29. // AS_PATH_LIST 返回path
  30. //SUPPRESS_EXCEPTIONS
  31. // 不抛出异常,需要判断如下:
  32. //
  33. // ALWAYS_RETURN_LIST开启,则返回空list
  34. // ALWAYS_RETURN_LIST关闭,则返回null
  35. //REQUIRE_PROPERTIES 如果设置,则不允许使用通配符,比如$[*].b,会抛出PathNotFoundException异常
  36. Configuration conf2 = configuration1.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
  37. //Works fine
  38. String gendc= using(conf2).parse(json).read("$.store.book[0]['gender']");
  39. //Works fine (null is returned)
  40. String genders = using(conf2).parse(json).read("$.store.book[1]['gender']");
  41. System.out.println(gendc);
  42. System.out.println(genders);
  43. }

发表评论

表情:
评论列表 (有 0 条评论,119人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JsonPath 运算符使用

    背景 因为之前用到Jmeter的Json 提取器涉及到JsonPath的使用,因此查找了一些文章,将里面的精华部分运算符的使用提取出来记录以下,方便自己以后使用。 J