第一步,導入jsonPath所需jar包(json-path-0.8.1.jar,json-smart-1.1.1.jar,commons-lang-2.6.jar),下載地址:https://download.csdn.net/download/cling_snail/10531694。
第二步,使用jsonPath解析數據,下面是jsonPath的簡單語法和示例:
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數組的長度 |
以上是一些簡單的jsonpath語法示例。
下面是我項目中使用的jsonpath,因爲我的項目是集成高德地圖,通過高德api接口發送地址,獲取到高德返回的地址經緯度,所以需要解析高德返回的json數據。
mian方法中調用接口:
//發送 POST 請求
String sr=HttpRequest.sendPost("https://restapi.amap.com/v3/geocode/geo", "address=天津市河東區大王莊六緯路與十四徑路交口&output=JSON&key=自己在高德上申請的web端key值");
//獲取高德地圖服務器返回的json格式數據
System.out.println("狀態:"+json2String(sr,"$..status")); //獲取到json中所有的status值
System.out.println("地址:"+json2String(sr,"$..formatted_address")); //獲取到json中所有的formatted_address值
System.out.println("經緯度:"+json2String(sr,"$..location")); //獲取到json中所有的location值
其中的sr爲json格式的數據:{"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"天津市河東區六緯路/十四徑路","province":"天津市","citycode":"022","city":"天津市","district":"河東區","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"120102","street":[],"number":[],"location":"117.228002,39.116834","level":"道路交叉路口"}]}
解析結果:
好了,此時就能解析出json數據了,是不是很簡單,假如不使用jsonPath,就要通過一層一層的遍歷獲取json數據中的值,增加了代碼的複雜度和工作量。