工作中有将json的key全部转成大写的场景,网上搜索了一圈,发现都没有使用fastjson的,所以决定自己手搓一个小工具类,在此做个记录,仅供参考学习。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
public class test {
/**
* JSON的key转为大写,value为null则去掉
* @param json
* @param resultjson
* @return
*/
public static JSONObject toUpperCaseobject(String json, String resultjson) {
JSONObject jsonObject = JSONObject.parseObject(json);
JSONObject jsonObject2 = JSONObject.parseObject(resultjson);
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
if (checkJSONObject(entry.getValue().toString())) {//jsonobject
jsonObject2.put(entry.getKey().toUpperCase(), toUpperCaseobject(entry.getValue().toString(),
jsonObject2.getString(entry.getKey())));
jsonObject2.remove(entry.getKey());
} else if (checkArray(entry.getValue().toString())) {//jsonarry
JSONArray array = JSONArray.parseArray(entry.getValue().toString());
for (int i = 0; i < array.size(); i++) {
JSONObject j1 = (JSONObject) array.get(i);
JSONObject j2 = j1;
array.set(i, toUpperCaseobject(j1.toJSONString(), j2.toJSONString()));
}
jsonObject2.put(entry.getKey().toUpperCase(), array);
jsonObject2.remove(entry.getKey());
} else {//到达底层
jsonObject2.put(entry.getKey().toUpperCase(), jsonObject2.getString(entry.getKey().toUpperCase()) != null
? jsonObject2.getString(entry.getKey().toUpperCase()) : jsonObject2.getString(entry.getKey()));
jsonObject2.remove(entry.getKey());
}
}
return jsonObject2;
}
/**
* 判断是否是JSONObject
* @param text
* @return
*/
public static boolean checkJSONObject(String text) {
try {
JSONObject object = JSON.parseObject(text);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 判断是否是JSONArry
* @param text
* @return
*/
public static boolean checkArray(String text) {
try {
JSONArray array = JSONArray.parseArray(text);
return true;
} catch (Exception e) {
return false;
}
}
}