首先约定json表示节点的规则,如
{
"data": {
"req": [{
"node1": "value1",
"node2": "value2"
}, {
"node3": "value3",
"node4": "value4"
}]
}
}
要获取node2的值时,规则应该填写JSON.data.req[0].node2
要获取node3的值时,规则应该填写JSON.data.req[1].node3
下面提供方法解析获取具体的值
/**
* 对节点进行解析
*
* @param obj
* @param node
* @return
*/
private static JSONObject getObj(JSONObject obj, String node) {
try {
if(node.contains("[")) {
JSONArray arr = obj.getJSONArray(node.substring(0, node.indexOf("[")));
for(int i = 0; i < arr.size(); i++) {
if ((i + "").equals(node.substring(node.indexOf("["), node.indexOf("]")).replace("[", ""))) {
return arr.getJSONObject(i);
}
}
} else {
return obj.getJSONObject(node);
}
} catch(Exception e) {
return obj;
}
return null;
}
/**
* 获取节点值
* @param jsonContent
* @param jsonPath
* @return
* @throws Exception
*/
public static synchronized String getNodeValue(String jsonContent, String jsonPath) throws Exception {
String[] nodes = jsonPath.split("\\.");
JSONObject obj = JSONObject.parseObject(jsonContent);
for (int i = 1; i < nodes.length; i++) {
if (obj != null) {
obj = getObj(obj, nodes[i]);
}
if ((i+1) == nodes.length) {
try {
return obj.getString(nodes[i]);
} catch(Exception e) {
return "JSONException:" + e.getMessage() + ", NodeString:" + obj.toString();
}
}
}
return null;
}