在项目里 业务要求要把两层的分级 变成一层存入,为此参考了其他博主的代码进行了一点修改,记录在工作笔记中。
//这里是两级分层 ,以下是测试数据
//入参为 转为json的字串形式
//json 平铺方法
// Integer record = 0;//递归初始数
// Integer flattenNumb = 2;// 平铺分层数
public static JSONObject flattenByRecord(String jsonStr, Integer record, Integer flattenNumb ){
JsonElement tree = JsonParser.parseString(jsonStr);
//System.out.println(tree.isJsonObject());//true
JsonObject jo = (JsonObject)tree;
JsonObject fa = new JsonObject();
String father = "";
//System.out.println(flatten(jo,fa,father));
JsonObject resultJo = flatten(jo,fa,father,record,flattenNumb);
String flattenStr = new Gson().toJson(resultJo);
JSONObject outputData = JSONUtil.parseObj(flattenStr);
return outputData;
}
private static JsonObject flatten(JsonObject object, JsonObject flattened, String father, Integer record,Integer flattenNumb){
//flatten递归函数实现对多层json的扁平化处理解析,第三个形参仅仅用来保留外层的键并在之后进行拼接
record+=1;//递归调用次数
if(flattened == null){
flattened = new JsonObject();
}
// Iterator keys =(Iterator) object.keySet();
for(Map.Entry entry : object.entrySet()){
String midFather = entry.getKey().toString();
String tmp = father;
JsonElement tmpVa = (JsonElement) entry.getValue();
try{
if(tmpVa.isJsonObject()){
//检测到多层json的时候进行递归处理
tmp = tmp +"." + midFather;//当前层键与之前外层键进行拼接
//System.out.println("aaa"+entry.getKey().toString()+"--------"+tmp);
if (record == 1){
flatten(object.getAsJsonObject(entry.getKey().toString()),flattened,tmp,record,flattenNumb);
// record+=1;
}
if (flattenNumb == record){
//当前层的值没有嵌套json键值对,直接将键值对添加到flattened中
String nowKeyTmp = father + "." + entry.getKey().toString();
String nowKey = nowKeyTmp.substring(1,nowKeyTmp.length());
flattened.add(nowKey,((JsonElement) entry.getValue()));
}
} else {
//当前层的值没有嵌套json键值对,直接将键值对添加到flattened中
String nowKeyTmp = father + "." + entry.getKey().toString();
String nowKey = nowKeyTmp.substring(1,nowKeyTmp.length());
flattened.add(nowKey,((JsonElement) entry.getValue()));
// record = 0;
}
} catch (JsonIOException e) {
System.out.println(e);
}
}
return flattened;
}
参考博客:https://blog.csdn.net/studyhard232/article/details/81202449



