json-path
pom.xmldependencygroupIdcom.jayway.jsonpath/groupIdartifactIdjson-path/artifactIdversion2.9.0/version/dependencyjson文件内容{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.javaToStringDataclassBook{privateStringcategory;privateStringauthor;privateStringtitle;privatedoubleprice;}使用对杂乱无章的json格式字符串进行语法校验以及格式标准化Stringraw{ \name\ : \张三\ , \n \age\: 20 };ObjectstandardJson;try{standardJsonJsonPath.parse(raw).json();// LinkedHashMap}catch(InvalidJsonExceptione){System.out.println(json语法错误);}DocumentContextabcJsonPath.using(Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)).parse(raw);Stringnameabc.read($.name);// 张三解析后读取(适合多次读取)publicstaticvoidmain(String[]args)throwsException{StringjsonreadResourceJsonFile(a.json);// 解析后读取适合多次读取DocumentContextdcJsonPath.using(Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)).parse(json);Integeradc.read($.store.sjkfsdlkf);// 没查到返回null而不是抛异常}publicstaticStringreadResourceJsonFile(StringfilePath)throwsIOException{ClassPathResourceresourcenewClassPathResource(filePath);try(InputStreamReaderreadernewInputStreamReader(resource.getInputStream(),StandardCharsets.UTF_8)){returnFileCopyUtils.copyToString(reader);}}}$.store.book[*].titleListStringtitleListdc.read($.store.book[*].title);// [标题1,标题2]$.store.book[1].pricedoubleprice2dc.read($.store.book[1].price);// 2.4$.store.book[0,2].authorListStringauthorListdc.read($.store.book[0,2].author);// [作者1,zs]$.store.book.length()intlengthdc.read($.store.book.length());// 3存在title的$.store.book[?(.title)]// 以下两种用map或者string接收都可以ListMapString,Objectaaadc.read($.store.book[?(.title)]);ListStringbbbdc.read($.store.book[?(.title)]);aaa、bbb是上一步的返回结果$[*].author// 其实第一个参数用map或者string都可以ListStringcccJsonPath.read(aaa,$[*].author);// [作者1,作者2]ListStringdddJsonPath.read(bbb,$[*].author);// [作者1,作者2]$.store.book[?(.price 2)].authorListStringeeedc.read($.store.book[?(.price 2)].author);// [作者2,zs]$.store.book[?(.author $.store.master .price 3)].categoryListStringfffdc.read($.store.book[?(.author $.store.master .price 3)].category);// [类别3]limit(2)// limit截取避免大数据量的内存占用以及解析时间ListBookbookJsonPath.parse(json).limit(2).read($.store.book[*],List.class);