json-path
2026/8/7 9:41:57 网站建设 项目流程

pom.xml

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

json文件内容

{"store":{"master":"zs","book":[{"category":"类别1","author":"作者1","title":"标题1","price":1.2},{"category":"类别2","author":"作者2","title":"标题2","price":2.4},{"category":"类别3","author":"zs","price":3.6}],"bicycle":{"color":"红色","price":4.9}}}

Book.java

@ToString@DataclassBook{privateStringcategory;privateStringauthor;privateStringtitle;privatedoubleprice;}

使用

对杂乱无章的json格式字符串进行语法校验以及格式标准化

Stringraw="{ \"name\" : \"张三\" , \n \"age\": 20 }";ObjectstandardJson;try{standardJson=JsonPath.parse(raw).json();// LinkedHashMap}catch(InvalidJsonExceptione){System.out.println("json语法错误");}DocumentContextabc=JsonPath.using(Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)).parse(raw);Stringname=abc.read("$.name");// 张三

解析后读取(适合多次读取)

publicstaticvoidmain(String[]args)throwsException{Stringjson=readResourceJsonFile("a.json");// 解析后读取,适合多次读取DocumentContextdc=JsonPath.using(Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)).parse(json);Integera=dc.read("$.store.sjkfsdlkf");// 没查到返回null,而不是抛异常}publicstaticStringreadResourceJsonFile(StringfilePath)throwsIOException{ClassPathResourceresource=newClassPathResource(filePath);try(InputStreamReaderreader=newInputStreamReader(resource.getInputStream(),StandardCharsets.UTF_8)){returnFileCopyUtils.copyToString(reader);}}}

$.store.book[*].title

List<String>titleList=dc.read("$.store.book[*].title");// ["标题1","标题2"]

$.store.book[1].price

doubleprice2=dc.read("$.store.book[1].price");// 2.4

$.store.book[0,2].author

List<String>authorList=dc.read("$.store.book[0,2].author");// ["作者1","zs"]

$.store.book.length()

intlength=dc.read("$.store.book.length()");// 3

存在title的:$.store.book[?(@.title)]

// 以下两种用map或者string接收都可以List<Map<String,Object>>aaa=dc.read("$.store.book[?(@.title)]");List<String>bbb=dc.read("$.store.book[?(@.title)]");

aaa、bbb是上一步的返回结果:$[*].author

// 其实第一个参数用map或者string都可以List<String>ccc=JsonPath.read(aaa,"$[*].author");// ["作者1","作者2"]List<String>ddd=JsonPath.read(bbb,"$[*].author");// ["作者1","作者2"]

$.store.book[?(@.price >2)].author

List<String>eee=dc.read("$.store.book[?(@.price >2)].author");// ["作者2","zs"]

$.store.book[?(@.author == $.store.master && @.price > 3)].category

List<String>fff=dc.read("$.store.book[?(@.author == $.store.master && @.price > 3)].category");// ["类别3"]

limit(2)

// limit截取,避免大数据量的内存占用以及解析时间List<Book>book=JsonPath.parse(json).limit(2).read("$.store.book[*]",List.class);

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询