package com.example.utils;
|
|
import cn.hutool.json.JSON;
|
import cn.hutool.json.JSONArray;
|
import cn.hutool.json.JSONObject;
|
import com.example.constant.FieldNameMapping;
|
|
import java.util.Map;
|
|
/**
|
* 解析JSON
|
* 字段统一处理类
|
*/
|
public class FieldNameConverter {
|
|
public static JSON convertFieldNames(JSON json) {
|
if (json instanceof JSONObject) {
|
return convertJSONObject((JSONObject) json);
|
} else if (json instanceof JSONArray) {
|
return convertJSONArray((JSONArray) json);
|
}
|
return json;
|
}
|
|
private static JSONObject convertJSONObject(JSONObject jsonObject) {
|
JSONObject newJsonObject = new JSONObject();
|
for (String key : jsonObject.keySet()) {
|
String newKey = FieldNameMapping.FIELD_MAPPING.getOrDefault(key.toLowerCase(), key);
|
Object value = jsonObject.get(key);
|
|
if (value instanceof JSONObject) {
|
newJsonObject.putOpt(newKey, convertJSONObject((JSONObject) value));
|
} else if (value instanceof JSONArray) {
|
newJsonObject.putOpt(newKey, convertJSONArray((JSONArray) value));
|
} else {
|
newJsonObject.putOpt(newKey, value);
|
}
|
}
|
return newJsonObject;
|
}
|
|
private static JSONArray convertJSONArray(JSONArray jsonArray) {
|
JSONArray newArray = new JSONArray();
|
for (Object item : jsonArray) {
|
if (item instanceof JSONObject) {
|
newArray.add(convertJSONObject((JSONObject) item));
|
} else if (item instanceof JSONArray) {
|
newArray.add(convertJSONArray((JSONArray) item));
|
} else {
|
newArray.add(item);
|
}
|
}
|
return newArray;
|
}
|
}
|