输入json格式字符串
输出{
"a": "1",
"b": "2",
"c": {
"d": "33",
"e": [
"4",
"5"
]
, "h": "6"
},
"j": "7"
}
输出为字符串数组,格式为a.b.c
设计思路[
a.1,
b.2,
c.d.33,
c.e.["4","5"],
c.h.6,
j.7
]
1、首先将json格式的字符串通过fastjson转换成JSONObject
2、获取JSONObject的所有的key,依次访问;如果通过key访问到的值是JSONObject类型,则继续调用递归方法
3、使用ArrayList
4、当访问到的value不是JSONObject之后,意味着调用到了最内层的key:value键值对,将对应路径存放到strList中
5、当从内部递归函数返回到外层递归函数中时,需要将path最后添加的一个元素移除掉
添加的依赖包代码实现com.alibaba fastjson1.2.71
public class Main {
//存放最终结果
static ArrayList strList=new ArrayList();
public static void main(String[] args) {
String json = "{n" +
" "a": "1",n" +
" "b": "2",n" +
" "c": {n" +
" "d": "33",n" +
" "e": [n" +
" "4",n" +
" "5"n" +
" ]n," +
" "h": "6"n" +
" },n" +
" "j": "7"n" +
"}";
//解析成JSonObject
JSonObject jsonObject = parseJson(json);
//存放当前递归访问的路径
ArrayList path=new ArrayList();
//获取最终结果
getResult(jsonObject,path);
System.out.println("strList->"+strList);
System.out.println("path->"+path);
}
private static JSonObject parseJson(String json) {
JSonObject parse = JSON.parseObject(json);
return parse;
}
public static void getResult(JSonObject object,ArrayList path) {
Set keySet = object.keySet();
for (String key : keySet) {
path.add(key+".");
if (object.get(key) instanceof JSONObject) {
getResult(object.getJSonObject(key),path);
} else {
String temp="";
for(String s:path){
temp+=s;
}
strList.add(temp+object.get(key).toString());
}
path.remove(path.size()-1);
}
}
}
测试结果



