-
递归获取指定key的值
/**
* 递归获取指定key的值
*
* @param json 待查询的json对象
* @param key 需要查询的key
* @return 查询到的值,如果key不存在或者值为null,则返回null
*/
public static Object getValueLoop(JSONObject json, String key) {
if (json == null || key == null) {
return null;
}
// 如果当前json包含此key,则直接返回
if (json.containsKey(key)) {
return json.get(key);
}
for (Map.Entry<String, Object> entry : json.entrySet()) {
Object value = entry.getValue();
if (value instanceof JSONObject) {
Object result = getValueLoop(JSON.parseObject(value.toString()), key);
if (result != null) {
return result;
}
} else if (value instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) value;
for (int i = 0; i < jsonArray.size(); i++) {
Object result = getValueLoop(jsonArray.getJSONObject(i), key);
if (result != null) {
return result;
}
}
}
}
return null;
}
-
根据链式键获取值
/**
* 从JSON对象中根据链式键获取值。
*
* @param json 要搜索的JSON对象。
* @param chainKey 链式键,使用"."分隔多层键,支持数组访问(如:key[0])。
* @return 根据链式键找到的值,如果找不到或参数无效则返回null。
*/
public static Object getValueChain(JSONObject json, String chainKey) {
// 检查输入参数是否有效
if (json == null || chainKey == null) {
return null;
}
Object result = json;
// 分割链式键为单个键名
String[] keys = chainKey.split("\\.");
for (String key : keys) {
if (key.contains("[") && key.contains("]")) {
// 处理数组访问形式的键
String[] keyArray = key.split("\\[");
JSONArray array = (JSONArray) getValueLoop(JSONObject.parseObject(result.toString()), keyArray[0]);
if (array == null) {
return null;
}
int index = Integer.parseInt(keyArray[1].replace("]", ""));
if (array.size() < index) return null;
result = array.getJSONObject(index); // 获取指定索引的JSON对象
} else {
// 处理普通键
result = getValueLoop(JSONObject.parseObject(result.toString()), key);
}
}
return result;
}