JsonPath —— JSON 解析神器

真乃神器也,再複雜的 Json 都能給你解析出來,非常方便的獲取 JSON 的內容,很強大!

語法簡介

JSON 值:

{ "store": {n "book": [n { "category": "reference",n "author": "Nigel Rees",n "title": "Sayings of the Century",n "price": 8.95n },n { "category": "fiction",n "author": "Evelyn Waugh",n "title": "Sword of Honour",n "price": 12.99,n "isbn": "0-553-21311-3"n }n ],n "bicycle": {n "color": "red",n "price": 19.95n }n }n}n

導包:import com.jayway.jsonpath.JsonPath

解析代碼:

//輸出book[0]的author值nString author = JsonPath.read(json, "$.store.book[0].author");nSystem.out.println("authort"+author);n//輸出全部author的值,使用Iterator迭代nList<String> authors = JsonPath.read(json, "$.store.book[*].author");nSystem.out.println("authorst"+authors);n//輸出book[*]中category == reference的booknList<Object> books = JsonPath.read(json, "$.store.book[?(@.category == reference)]");nSystem.out.println("bookst"+books);n//輸出book[*]中category == reference的book或者nList<Object> books2 = JsonPath.read(json, "$.store.book[?(@.category == reference || @.price>10)]");nSystem.out.println("books2t"+books2);n//輸出book[*]中category == reference的book的authornList<Object> books1 = JsonPath.read(json, "$.store.book[?(@.category == reference)].author");nSystem.out.println("books1t"+books1);n//輸出book[*]中price>10的booknList<Object> b1 = JsonPath.read(json, "$.store.book[?(@.price>10)]");nSystem.out.println("b1"+b1);n//輸出book[*]中含有isbn元素的booknList<Object> b2 = JsonPath.read(json, "$.store.book[?(@.isbn)]");nSystem.out.println("b2"+b2);n//輸出該json中所有price的值nList<Double> prices = JsonPath.read(json, "$..price");nSystem.out.println("prices"+prices);n//輸出該json中所有title的值nList<Double> title = JsonPath.read(json, "$..title");nSystem.out.println("title"+title);n//輸出該json中book 0,1的值nList<Double> book01 = JsonPath.read(json, "$..book[0,1]");nSystem.out.println("book01"+book01);n/* //輸出該json中book 0,1的值nList<Double> book012 = JsonPath.read(json, "$..book[-2:]");nSystem.out.println("book012"+book012);*/n//可以提前編輯一個路徑,並多次使用它nJsonPath path = JsonPath.compile("$.store.book[*]");nList<Object> b3 = path.read(json);nSystem.out.println("patht"+path+"n"+b3);n

用法比較簡單,多使用幾次就會使用了!文章主要參考網上!原諒很多天不跟博的我現在竟然這樣水了這麼一篇文章,哈哈!實在是忙!

作者:Zhisheng Tian

原文地址:54tianzhisheng.cn/2017/

版權說明:本文由極樂科技(dreawer.com)簽約作者供稿,版權歸作者所有,轉載請保留版權,有什麼問題,請聯繫我們,謝謝!

推薦閱讀:

TAG:JSON | JSONWebTokens | jsonrpc |