由于遇到了奇葩甲方,需要将数据格式转成下划线的格式,但是我们项目都是按照标准驼峰格式,所以写了个工具类来转换,不仅仅限于驼峰和下划线,根据需要传入
有没有大佬把这个递归改成迭代的
使用到的依赖
fastjon
google的guava工具包
自己的包名;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import java.util.Objects;
import java.util.Set;
public class JsonUtil {
public static <T extends JSON> void lowerCaseToUnderline(T json) {
jsonKeyConverter(json, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_UNDERSCORE);
}
public static <T extends JSON> void underlineToLowerCase(T json) {
jsonKeyConverter(json, CaseFormat.LOWER_UNDERSCORE, CaseFormat.LOWER_CAMEL);
}
public static <T extends JSON> void jsonKeyConverter(T json, CaseFormat from, CaseFormat to) {
if (Objects.isNull(json)) {
return;
}
if (json instanceof JSONObject jsonObject) {
Set<String> keySet = jsonObject.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
for (String key : keyArray) {
Object o = jsonObject.get(key);
if (o instanceof JSON json1) {
jsonKeyConverter(json1, from, to);
}
Object value = jsonObject.remove(key);
String newKey = from.to(to, key);
jsonObject.put(newKey, value);
}
}
if (json instanceof JSONArray jsonArray) {
for (Object o : jsonArray) {
if (o instanceof JSON json1) {
jsonKeyConverter(json1, from, to);
}
}
}
}
public static void main(String[] args) {
String s = """
{
"user": [
{
"id": 34,
"userName": "test_e33814e11c68",
"isDel": 32,
"createTime": "2024-01-31 15:08:40",
"updateTime": "2014-05-13 04:13:20",
"createBy": "test_c6aafd546ac1",
"updateBy": "test_31f6b077a3ef"
}
]
}
""";
JSONObject jsonObject = JSON.parseObject(s);
lowerCaseToUnderline(jsonObject);
System.out.println(jsonObject);
}
}