1.ExpressUtils 工具:https://blog.csdn.net/bestxianfeng163/article/details/105856610
2.HumpLineUtils工具:https://blog.csdn.net/bestxianfeng163/article/details/102589532
package com.zycfc.mpc.process.util;
import java.util.Set;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class JsonHumpLineUtils {
public static void main(String[] args) {
String json2="{}";
System.out.println(transfer(json2));
}
/*
* 遞歸駝峯json 轉化下劃線json
*/
public static JSONObject transfer(String json) {
JSONObject objTem = JSON.parseObject(json);
return transHump(objTem);
}
/*
* 遞歸Json駝峯轉下劃線json
* */
private static JSONObject transLine(JSONObject objTem) {
JSONObject jsonObject = new JSONObject();
Set<String> keySet = objTem.keySet();
for (String key : keySet) {
Object objR = objTem.get(key);
Class type = objR.getClass();
String express = ExpressUtils.getExpress(ExpressUtils.classLists());
if (ExpressUtils.judge(express, type)) {
jsonObject.put(HumpLineUtils.transline(key, "Lower"), objR);
continue;
}
if (objR instanceof JSONObject) {
JSONObject deal = transLine((JSONObject) objR);
jsonObject.put(HumpLineUtils.transline(key, "Lower"), deal);
continue;
}
if (objR instanceof JSONArray) {
JSONArray jsonA = new JSONArray();
JSONArray jsonArray = objTem.getJSONArray(key);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonDeal = transLine(jsonArray.getJSONObject(i));
jsonA.add(jsonDeal);
}
jsonObject.put(HumpLineUtils.transline(key, "Lower"), jsonA);
}
}
return jsonObject;
}
/*
* 遞歸下劃線Json轉駝峯json
* */
private static JSONObject transHump(JSONObject objTem) {
JSONObject jsonObject = new JSONObject();
Set<String> keySet = objTem.keySet();
for (String key : keySet) {
Object objR = objTem.get(key);
Class type = objR.getClass();
String express = ExpressUtils.getExpress(ExpressUtils.classLists());
if (ExpressUtils.judge(express, type)) {
jsonObject.put(HumpLineUtils.transHump(key), objR);
continue;
}
if (objR instanceof JSONObject) {
JSONObject deal = transHump((JSONObject) objR);
jsonObject.put(HumpLineUtils.transHump(key), deal);
continue;
}
if (objR instanceof JSONArray) {
JSONArray jsonA = new JSONArray();
JSONArray jsonArray = objTem.getJSONArray(key);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonDeal = transHump(jsonArray.getJSONObject(i));
jsonA.add(jsonDeal);
}
jsonObject.put(HumpLineUtils.transHump(key), jsonA);
}
}
return jsonObject;
}
}