以下是利用JSONPath对JSONObject的操作示例代码:
public static void main(String[] args) {
JSONObject json=new JSONObject();
json.put("name","张三");
json.put("sex","女");
json.put("address","浙江杭州西湖转塘");
JSONObject son=new JSONObject();
son.put("name","小明");
son.put("sex","男");
son.put("address","浙江杭州萧山宁围");
json.put("son",son);
System.out.println("原先:"+json.toJSONString());
JSONPath.set(json,"$.name","小风");
System.out.println("现在:"+json.toJSONString());
String name =(String) JSONPath.eval(json, "name");
System.out.println("name:"+name);
System.out.println(JSONPath.contains(json,"hhh"));
Map<String, Object> paths = JSONPath.paths(json);
System.out.println(paths);
}
输出结果如下:
原先:{"address":"浙江杭州西湖转塘","son":{"address":"浙江杭州萧山宁围","sex":"男","name":"小明"},"sex":"女","name":"张三"}
现在:{"address":"浙江杭州西湖转塘","son":{"address":"浙江杭州萧山宁围","sex":"男","name":"小明"},"sex":"女","name":"小风"}
name:小风
false
{/son/address=浙江杭州萧山宁围, /sex=女, /name=小风, /son={"address":"浙江杭州萧山宁围","sex":"男","name":"小明"}, /son/sex=男, /address=浙江杭州西湖转塘, /son/name=小明, /={"address":"浙江杭州西湖转塘","son":{"address":"浙江杭州萧山宁围","sex":"男","name":"小明"},"sex":"女","name":"小风"}}
总结常用的几种方法:
public class JSONPath {
//将对象中的属性与值的对应关系转换成 key=value 形式,key包含对象中的对象的属性,可以递归到最底层,这样可以用以直观的判断一个对象中所有的key=value 并操作
public static Map<String, Object> paths(Object javaObject, SerializeConfig config) {
Map<Object, String> values = new IdentityHashMap();
Map<String, Object> paths = new HashMap();
paths(values, paths, "/", javaObject, config);
return paths;
}
// 求值,静态方法
public static Object eval(Object rootObject, String path);
// 计算Size,Map非空元素个数,对象非空元素个数,Collection的Size,数组的长度。其他无法求值返回-1
public static int size(Object rootObject, String path);
// 是否包含,对象中是否包含该path
public static boolean contains(Object rootObject, String path) { }
// 是否包含,path中是否存在指定值,如果是集合或者数组,在集合中查找value是否存在
public static boolean containsValue(Object rootObject, String path, Object value) { }
// 修改指定路径的值,如果修改成功,返回true,否则返回false
public static boolean set(Object rootObject, String path, Object value) {}
// 在数组或者集合中添加元素
public static boolean array_add(Object rootObject, String path, Object... values);
}
path格式: $.key.key… $表示从根目录起,如上示例代码中
$.son.address=“浙江杭州萧山宁围” 表示jsonObject对象中son 对象里的address属性