2019独角兽企业重金招聘Python工程师标准>>>
//单元科技-www.ccell.com.cn 技术部,开源
//XML数据有XPATH 如"root/rows[@id=1]/name"
//在JS中JSON数据可以对象方式访问
//java中怎么 用字符串表达式访问JSON数据? 找了很久没有找到,自己写一个,以减小代码量,让程序可读性变强
//用法:
// JSONObject json = JSON.parseObject("{a:1,b:{}}");
// JSONHelper.putByJPath(json, "b.abc", 123);
// System.out.println(json);
// System.out.println(JSONHelper.getByJPath(json, "b.abc", Integer.class));
//代码:
package com.ccell.json;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class JSONHelper {
public static <T> Object getByJPath(JSONObject root, String jpath, Class<T> cls) {
if (root == null) {
return null;
}
if (jpath == null || "".equals(jpath)) {
if (cls.equals(JSONObject.class)){
return root;
}else{
return null;
}
}
String[] names = jpath.split("\\.");
String key = names[0];
JSONObject jobj = null;
Object result = null;
if (key.matches("^.+(\\[\\d+\\])+$")) {
String[] tmps = key.replaceAll("\\]", "").split("\\[");
JSONArray jarray = root.getJSONArray(tmps[0]);
if (jarray != null) {
for (int j = 1; j < tmps.length; j++) {
int index = Integer.parseInt(tmps[j]);
if (j == tmps.length - 1) {
if (names.length == 1) {
result = jarray.getObject(index, cls);
} else {
jobj = jarray.getJSONObject(index);
result = getByJPath(jobj, jpath.substring(key.length() + 1), cls);
}
} else {
jarray = jarray.getJSONArray(index);
}
}
}
} else {
if (names.length == 1) {
result = root.getObject(key, cls);
} else {
jobj = root.getJSONObject(key);
result = getByJPath(jobj, jpath.substring(key.length() + 1), cls);
}
}
return result;
}
public static void putByJPath(JSONObject root, String jpath, Object value) {
String key = jpath;
String parentpath = "";
int pos = jpath.lastIndexOf(".");
if (pos >= 0){
key = jpath.substring(pos + 1);
parentpath = jpath.substring(0,pos );
}
JSONObject jobj = (JSONObject) getByJPath(root,parentpath,JSONObject.class);
jobj.put(key, value);
}
}