解析處理Josn的好幫手--JsonPath

常見需求

1、讀取字符串中某個key的值,但是這個key的層級比較深

2、篩選出json字符串中符合條件的葉子節(jié)點

3、讀取某個key在json字符串中所有的值

4、替換json字符串中的某個key的值

5、移除json字符串中某個key

常用方法

1、map

2、map

3、map

4、set /put?

? ? ? 其中set方法只能在xpath存在的情況下執(zhí)行更新,put方法若指定的xpath 的key不存在,則添加,若存在,則執(zhí)行更新操作

5、delete

使用示例

public static void main(String[] args) {

String jsonStr ="{\n" +

"? ? \"store\": {\n" +

"? ? ? ? \"book\": [\n" +

"? ? ? ? ? ? {\n" +

"? ? ? ? ? ? ? ? \"category\": \"reference\",\n" +

"? ? ? ? ? ? ? ? \"author\": \"hhhhh\",\n" +

"? ? ? ? ? ? ? ? \"title\": \"Sayings of the Century\",\n" +

"? ? ? ? ? ? ? ? \"price\": 8.95\n" +

"? ? ? ? ? ? }\n" +

"? ? ? ? ],\n" +

"? ? ? ? \"bicycle\": {\n" +

"? ? ? ? ? ? \"color\": \"red\",\n" +

"? ? ? ? ? ? \"price\": 19.95\n" +

"? ? ? ? }\n" +

"? ? },\n" +

"? ? \"expensive\": 10\n" +

"}";

DocumentContext json = JsonPath.parse(jsonStr);

String setMethodPath ="$..book[0].author";

String tagValue ="ReplacedText";

String putMethodPath ="$..book[0]";

String newValue ="hahahha";

String deleteMethodPath ="$.expensive";

System.out.println(json.set(setMethodPath, tagValue).jsonString());

System.out.println(json.put(putMethodPath,"newKey", newValue).jsonString());

System.out.println(json.put(putMethodPath,"author","updateValue").jsonString());

System.out.println(json.delete(deleteMethodPath).jsonString());

}


依賴包

<dependency>

<groupId>com.jayway.jsonpath</groupId>

<artifactId>json-path</artifactId>

<version>2.4.0</version>

</dependency>

<dependency>

<groupId>net.minidev</groupId>

<artifactId>minidev-parent</artifactId>

<version>2.3</version>

</dependency>

參考

https://github.com/jayway/JsonPath

文檔

http://static.javadoc.io/com.jayway.jsonpath/json-path/2.2.0/com/jayway/jsonpath/WriteContext.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容