一、依赖
fastjson-1.2.83.jar
二、转换工具类 ConvertJsonKeyCase.java
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class ConvertJsonKeyCase {
/**
* 转换json对象key的大小写
*
* @param json json对象
* @param isUpper key是否转大写,true是,false否
* @return 转换后的json对象
*/
public static JSONObject convertJsonObjectKeyCase(JSONObject json, boolean isUpper) {
JSONObject JSONObject2 = new JSONObject();
for (String key : json.keySet()) {
Object object = json.get(key);
String newKey = isUpper ? key.toUpperCase() : key.toLowerCase();
// JSON对象
if (object instanceof JSONObject) {
JSONObject2.put(newKey, convertJsonObjectKeyCase((JSONObject) object, isUpper));
}
// JSON数组
else if (object instanceof JSONArray) {
JSONObject2.put(newKey, convertJsonArrayKeyCase(json.getJSONArray(key), isUpper));
}
// 值
else {
JSONObject2.put(newKey, object);
}
}
return JSONObject2;
}
/**
* 转换json数组key的大小写
*
* @param jsonArray json数组
* @param isUpper key是否转大写,true是,false否
* @return 转换后的json数组
*/
public static JSONArray convertJsonArrayKeyCase(JSONArray jsonArray, boolean isUpper) {
JSONArray jSONArray2 = new JSONArray();
for (Object object : jsonArray) {
// JSON对象
if (object instanceof JSONObject) {
jSONArray2.add(convertJsonObjectKeyCase((JSONObject) object, isUpper));
}
// JSON数组
else if (object instanceof JSONArray) {
jSONArray2.add(convertJsonArrayKeyCase((JSONArray) object, isUpper));
}
// 值
else {
jSONArray2.add(object);
}
}
return jSONArray2;
}
}
三、测试
package com.chenwc;
import com.alibaba.fastjson.JSONObject;
public class Main {
public static void main(String[] args) {
// TODO 自动生成的方法存根
String jsonString = "{\"ESB\":{\"DATA\":{\"DATAINFOS\":{\"DATAINFO\":[{\"Abbreviation\":\"深圳润园四季餐饮有限公司\",\"CityCode\":\"\",\"CooperationStatus\":\"合作中\",\"CATEGORYCODE\":\"00\",\"MULTICODE\":{\"VALUELIST\":[[\"ContactMobile\",\"IsPrimaryContact\",\"SfaContactId\",\"SPECIALITYCODE\",\"LISTCODE\",\"ContactEMail\",{\"a\":\"test\",\"b\":\"btest\"}],{\"ContactMobile\":\"17365459878\",\"IsPrimaryContact\":\"否\",\"SfaContactId\":\"6788874131617504418\",\"SPECIALITYCODE\":\"CONTACTINFO\",\"LISTCODE\":\"6WQB8MA09Z4776I430SJPC2TU6K93UU4\",\"ContactEMail\":\"2233133@qq.com\",\"ContactName\":\"吴繁荣\"},{\"SiteContactName\":\"刘三\",\"SiteAddress\":\"测试77777\",\"SfaSiteId\":\"8480089929551622116\",\"SPECIALITYCODE\":\"SITEINFO\",\"SiteCityCode\":\"110000\",\"LISTCODE\":\"WAHVUTQXQP7S0GQ36Z562W0S9OZ3QYEG\",\"SiteContactMobile\":\"21878128337\"}]},\"FILES\":[{\"STOREPATH\":\"6055786081413437802/cm/202210/ea56e72f4c2249ad8dc732517b36a634.jpg\",\"FILETYPE\":\"image/jpg\"},{\"STOREPATH\":\"6055786081413437802/cm/202301/59d94e4583cf42d2aa321694c8f5f483.jpg\",\"FILETYPE\":\"image/jpg\"}]}]}}}}";
JSONObject jsonObject = JSONObject.parseObject(jsonString);
System.out.println(jsonObject.toJSONString());
System.out.println(ConvertJsonKeyCase.convertJsonObjectKeyCase(jsonObject, false));
System.out.println(ConvertJsonKeyCase.convertJsonObjectKeyCase(jsonObject, true));
}
}