直接上代碼(遞歸有風險,棧太深會溢出,可考慮使用while代替)
遞歸實現:
/**
* @Auther: liuzujie
* @Date: 2020/2/26 16:25
* @Desc:
* @return: 考慮嵌套中會有key重複的情況,所以用IdentityHashMap
*/
public static IdentityHashMap getKeyVal(Object str, IdentityHashMap<String, Object> retMap) {
JSONObject json;//alibaba.fastjson
//JSON.parseObject只接受key-value形式,像【["直接是個數組", "沒有key-value", "不是對象"]】這種需要轉成JSONArray的不支持
json = JSON.parseObject(str.toString());
Set<String> keys = json.keySet();
for (String key : keys) {
Object value = json.get(key);
if (isPriStr(value)) {
retMap.put(new String(key), value);
} else if (value instanceof JSONObject) {
checkValue(value, retMap);
} else if (value instanceof JSONArray) {
JSONArray array = ((JSONArray) value);
for (int i = 0; i < array.size(); i++) {
if (isPriStr(array.get(i))) {
retMap.put(new String(key), value);
} else {
checkValue(array.get(i), retMap);
}
}
}
}
return retMap;
}
測試類:
/**
* @Auther: liuzujie
* @Date: 2020/2/26 16:35
* @Desc: 測試類
*/
public static void main(String[] args) {
IdentityHashMap<String, Object> dd = new IdentityHashMap<>();
getKeyVal("{\n" +
" \"name\": \"如果我是Dj\",\n" +
" \"age\": 26,\n" +
" \"test\": 3232,\n" +
" \"sb\": \"xiaoz\",\n" +
" \"list\": [\n" +
" {\n" +
" \"name\": \"你真的DJ嗎\",\n" +
" \"age\": 333,\n" +
" \"test\": 333,\n" +
" \"sb\": \"alErt\",\n" +
" \"list\": [\n" +
" {\n" +
" \"name\": \"嗨起來\",\n" +
" \"age\": 333,\n" +
" \"test\": 333,\n" +
" \"sb\": \"scridpt\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}", dd);
System.out.println(dd);
}
輸出: