JsonPath--使用
JsonPath:用来解析json,通过表达式获取方便获取json中的数据。
学习连接:https://github.com/json-path/JsonPath
参考连接:https://www.cnblogs.com/aoyihuashao/p/8665873.html
测试:
实体类:
@Data
public class MyFactory {
private Store store;
}
@Data
public class Store {
private String storeName;
private String stroeAddress;
private String version;
private List<Book> book;
}
@Data
public class Book {
private String category;
private String author;
private String title;
private String isbn;
private Integer price;
}
获取json字符串:
@Before
public void getJson(){
MyFactory myFactory=new MyFactory();
Store store=new Store();
List<Book> bookList=new ArrayList<>();
Book book=new Book();
book.setAuthor("Nigel Rees");
book.setCategory("reference");
book.setPrice(1);
book.setTitle("Sayings of the Century");
Book book1=new Book();
book1.setAuthor("Herman Melville");
book1.setCategory("fiction");
book1.setIsbn("0-553-21311-3");
book1.setPrice(2);
book1.setTitle("Moby Dick");
Book book2=new Book();
book2.setAuthor("J. R. R. Tolkien");
book2.setCategory("reference");
book2.setPrice(3);
book2.setIsbn("0-395-19395-8");
book2.setTitle("The Lord of the Rings");
bookList.add(book);
bookList.add(book1);
bookList.add(book2);
store.setStoreName("书店");
store.setStroeAddress("中国");
store.setVersion("1.0");
store.setBook(bookList);
myFactory.setStore(store);
Gson gson=new Gson();
json= gson.toJson(myFactory);
}
测试通配符:
/**
* $ 要查询的根元素。这将启动所有路径表达式。
* @ 当前节点由过滤谓词处理。
* * 通配符。可在任何名称或数字需要的地方使用。
* .. 深层扫描。可在任何需要名称的地方使用。
* .<name> 有点儿的孩子
* ['<name>' (, '<name>')] 带支架的儿童或儿童
* [<number> (, <number>)] 数组索引或索引
* [start:end] 数组切片运算符
* [?(<expression>)] 过滤表达式。表达式必须求值为布尔值。
*/
@Test
public void test1(){
List<String> authorList = JsonPath.read(json, "$.store.book[*].author");
System.out.println(authorList);
System.out.println("-------------------------------------");
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
String author0 = JsonPath.read(document, "$.store.book[0].author");
String author1 = JsonPath.read(document, "$.store.book[1].author");
System.out.println(author0);
System.out.println(author1);
}
测试返回类型:
/**
* 确定返回类型
*/
@Test
public void test2(){
//解析json将其中数据放置到ReadContext
ReadContext ctx = JsonPath.parse(json);
//转成list
List authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author", List.class);
System.out.println(authorsOfBooksWithISBN);
System.out.println("-------------------------------------");
Configuration configuration=Configuration.defaultConfiguration();
List<Map<String, Object>> expensiveBooks = using(configuration)
.parse(json)
.read("$.store.book[?(@.price > 10)]", List.class);
System.out.println(expensiveBooks);
System.out.println("-------------------------------------");
//将json中的某个字段转成另一个类型
String json1 = "{\"date_as_long\" : 1411455611975}";
Date date = JsonPath.parse(json1).read("$['date_as_long']", Date.class);
System.out.println(date);
System.out.println("-------------------------------------");
Book bookinfo = JsonPath.parse(json).read("$.store.book[0]", Book.class);
System.out.println(bookinfo);
}
测试过滤条件:
/**
* Predicates 过滤条件
*/
@Test
public void test3(){
//list中放置map
List<Map<String, Object>> books = JsonPath.parse(json) .read("$.store.book[?(@.price < 10)]");
Filter cheapFictionFilter = Filter.filter(
Criteria.where("category").is("fiction").and("price").lte(10D)
);
List<Map<String, Object>> bookmap =
JsonPath.parse(json).read("$.store.book[?]", cheapFictionFilter);
System.out.println(bookmap);
System.out.println("-------------------------------------");
// Filters can also be combined with 'OR' and 'AND'
Filter fooOrBar = Filter.filter(
Criteria.where("foo").exists(true)).or(where("bar").exists(true)
);
Filter fooAndBar = Filter.filter(
Criteria.where("foo").exists(true)).and(where("bar").exists(true)
);
Predicate booksWithISBN = new Predicate() {
@Override
public boolean apply(PredicateContext ctx) {
return ctx.item(Map.class).containsKey("isbn");
}
};
List<Map<String, Object>> booksList =JsonPath.parse(json).read("$.store.book[?].isbn", List.class, booksWithISBN);
Configuration conf = Configuration.builder().options(Option.AS_PATH_LIST).build();
List<String> pathList = JsonPath.using(conf).parse(json).read("$..author");
}
测试配置类Option:
Option:
package com.jayway.jsonpath;
public enum Option {
/**
* returns <code>null</code> for missing leaf.
*
* <pre>
* [
* {
* "foo" : "foo1",
* "bar" : "bar1"
* }
* {
* "foo" : "foo2"
* }
* ]
*</pre>
*
* the path :
*
* "$[*].bar"
*
* Without flag ["bar1"] is returned
* With flag ["bar1", null] is returned
*当检索不到时返回null对象,否则如果不配置这个,会直接抛出异常PathNotFoundException
*
*/
DEFAULT_PATH_LEAF_TO_NULL,
/**
* Makes this implementation more compliant to the Goessner spec. All results are returned as Lists.
总是返回list,即便是一个确定的非list类型,也会被包装成list。
*/
ALWAYS_RETURN_LIST,
/**
* Returns a list of path strings representing the path of the evaluation hits
返回path
*/
AS_PATH_LIST,
/**
* Suppress all exceptions when evaluating path.
* <br/>
* If an exception is thrown and the option {@link Option#ALWAYS_RETURN_LIST} an empty list is returned.
* If an exception is thrown and the option {@link Option#ALWAYS_RETURN_LIST} is not present null is returned.
不抛出异常,需要判断如下:
ALWAYS_RETURN_LIST开启,则返回空list
ALWAYS_RETURN_LIST关闭,则返回null
*/
SUPPRESS_EXCEPTIONS,
/**
* Configures JsonPath to require properties defined in path when an <bold>indefinite</bold> path is evaluated.
*
*
* Given:
*
* <pre>
* [
* {
* "a" : "a-val",
* "b" : "b-val"
* },
* {
* "a" : "a-val",
* }
* ]
* </pre>
*
* evaluating the path "$[*].b"
*
* If REQUIRE_PROPERTIES option is present PathNotFoundException is thrown.
* If REQUIRE_PROPERTIES option is not present ["b-val"] is returned.
如果设置,则不允许使用通配符,比如$[*].b,会抛出PathNotFoundException异常
*/
REQUIRE_PROPERTIES
}
测试:
/**
* Option
* [
* {
* "name" : "john",
* "gender" : "male"
* },
* {
* "name" : "ben"
* }
* ]
*
* Option的使用规则
*/
@Test
public void test4(){
Configuration configuration1 = Configuration.defaultConfiguration();
// //Works fine 报错
// String gender0 = using(configuration1).parse(json).read("$[0]['gender']");
// //PathNotFoundException thrown
// String gender1 = using(configuration1).parse(json).read("$[1]['gender']");
//
// System.out.println(gender0);
// System.out.println(gender1);
//
// System.out.println("------------------------------------");
//DEFAULT_PATH_LEAF_TO_NULL:当检索不到时返回null对象,否则如果不配置这个,会直接抛出异常PathNotFoundException
//ALWAYS_RETURN_LIST 总是返回list,即便是一个确定的非list类型,也会被包装成list。
// AS_PATH_LIST 返回path
//SUPPRESS_EXCEPTIONS
// 不抛出异常,需要判断如下:
//
// ALWAYS_RETURN_LIST开启,则返回空list
// ALWAYS_RETURN_LIST关闭,则返回null
//REQUIRE_PROPERTIES 如果设置,则不允许使用通配符,比如$[*].b,会抛出PathNotFoundException异常
Configuration conf2 = configuration1.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
//Works fine
String gendc= using(conf2).parse(json).read("$.store.book[0]['gender']");
//Works fine (null is returned)
String genders = using(conf2).parse(json).read("$.store.book[1]['gender']");
System.out.println(gendc);
System.out.println(genders);
}
还没有评论,来说两句吧...