给出一个JSON,根据指定的key(代码字段= path) 提JSON的字段
public static Object get(Object json, String path) {
if (json == null)
return null;
if (json instanceof String) {
String josnStr = ((String) json).trim();
if(josnStr.startsWith(“{”))
json = JSON.parseObject(josnStr);
else if(josnStr.startsWith(“[”))
json = JSON.parseArray(josnStr);
}
if (path == null || path.trim().length() == 0)
return json;
if (!(json instanceof JSONArray) && !(json instanceof JSONObject))
return null;
String cur = path;
String surplus = null;
if (path.contains(".")) {
cur = path.substring(0, path.indexOf("."));
surplus = path.substring(path.indexOf(".") + 1);
}
Matcher m = PATH_PATTERN.matcher(cur);
if (m.find()) {
int index = Integer.parseInt(m.group(2));
cur = m.group(1);
Object v = json;
if(!"".equals(cur)) {
if(json instanceof JSONArray)
json = ((JSONArray) json).get(0);
v = ((JSONObject) json).get(cur);
}
if (v instanceof JSONArray) {
return get(((JSONArray) v).get(index), surplus);
} else {
return get(v, surplus);
}
} else {
Object v = ((JSONObject) json).get(cur);
if (v instanceof JSONArray) {
return get(((JSONArray) v).get(0), surplus);
} else {
return get(v, surplus);
}
}
}