直接上代码(递归有风险,栈太深会溢出,可考虑使用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);
}
输出: