轉自:
https://www.cnblogs.com/gongxr/p/14251995.html
jsonpath就是json版的xmlPath,提供了類似xPath類似的方式來操作json,非常方便
import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; public class Test2 { public static void main(String[] args) { String json = "{\"objs\" : [{\"obj\" : 1411455611975}]}"; DocumentContext ext = JsonPath.parse(json); JsonPath p = JsonPath.compile("$.objs[0].obj"); ext.set(p, 141145561197333L); String author = ext.jsonString(); System.err.println(author); } }
/** * 根據路徑獲取值 * */ String bjnr = (String) JSONPath.read(json, "$.data.bjnr"); System.out.println("報警內容:" + bjnr); String isInvolved = (String) JSONPath.read(json, "$.data.isInvolved"); System.out.println("報警人是否是涉案人:" + isInvolved); /** * 獲取JSON中的對象數組 * */ List<JSONObject> hwList = (List<JSONObject>) JSONPath.read(json, "$.data.hwList"); System.out.println("hwList:" + hwList); /** * 獲取JSON中的所有id的值 * */ List<String> ids = (List<String>) JSONPath.read(json, "$..id"); System.out.println("ids:" + ids); /** * 可以提前編輯一個路徑,並多次使用它 * */ JSONPath path = JSONPath.compile("$.data.keywords"); System.out.println("keywords:" + path.eval(JSON.parseObject(json)));