//單元科技-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;java
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;json
public class JSONHelper {對象
public static <T> Object getByJPath(JSONObject root, String jpath, Class<T> cls) {字符串
if (root == null) {
return null;
}get
if (jpath == null || "".equals(jpath)) {
if (cls.equals(JSONObject.class)){
return root;
}else{
return null;
}
}
String[] names = jpath.split("\\.");
String key = names[0];string
JSONObject jobj = null;
Object result = null;it
if (key.matches("^.+(\\[\\d+\\])+$")) {ast
String[] tmps = key.replaceAll("\\]", "").split("\\[");class
JSONArray jarray = root.getJSONArray(tmps[0]);import
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); } }