最近工作中遇到json格式的字符串中的key为大写的,需要转换成小写的来解析,开始想使用正则来替换,结果不是很方便,后来考虑把JSONObject重新来封装。
如下json格式:{PWACHECKINFO:{QMART:”TEST”,NTNUM:”50”,ECRULE1:”测试中1”,ECRULE2:”,ECRULE3:”,ECRULE4:”,ECRULE5:”,ECRULE6:”,”}
public static void main(String[] args) {
JSONObject jsonObject = JSONObject.fromObject(json);
//方法一:重新解析jsonObject中的key,转换为小写的key
jsonObject = transToLowerObject(jsonObject);
System.out.println(jsonObject);
String regex = “(\{|\,)[a-zA-Z0-9]+:”;
Pattern pattern = Pattern.compile(regex);
StringBuffer sb = new StringBuffer();
// 方法二:正则替换
Matcher m = pattern.matcher(json);
while (m.find()) {
m.appendReplacement(sb, m.group().toLowerCase());
}
m.appendTail(sb);
String msg = sb.toString();
System.out.println(msg);
}
/**
* json大写转小写
*
* @param jSONArray1 jSONArray1
* @return JSONObject
*/
public static JSONObject transToLowerObject(JSONObject jSONArray1) {
JSONObject jSONArray2 = new JSONObject();
Iterator it = jSONArray1.keys();
while (it.hasNext()) {
String key = (String) it.next();
Object object = jSONArray1.get(key);
if (object.getClass().toString().endsWith(“String”)) {
jSONArray2.accumulate(key.toLowerCase(), object);
} else if (object.getClass().toString().endsWith(“JSONObject”)) {
jSONArray2.accumulate(key.toLowerCase(), transToLowerObject((JSONObject) object));
} else if (object.getClass().toString().endsWith(“JSONArray”)) {
jSONArray2.accumulate(key.toLowerCase(), transToArray(jSONArray1.getJSONArray(key)));
}
}
return jSONArray2;
}
/**
* jsonArray转jsonArray
*
* @param jSONArray1 jSONArray1
* @return JSONArray
*/
public static JSONArray transToArray(JSONArray jSONArray1) {
JSONArray jSONArray2 = new JSONArray();
for (int i = 0; i < jSONArray1.size(); i++) {
Object jArray = jSONArray1.getJSONObject(i);
if (jArray.getClass().toString().endsWith(“JSONObject”)) {
jSONArray2.add(transToLowerObject((JSONObject) jArray));
} else if (jArray.getClass().toString().endsWith(“JSONArray”)) {
jSONArray2.add(transToArray((JSONArray) jArray));
}
}
return jSONArray2;
}
转换后的格式如:
:{“qmart”:”TEST”,”ntnum”:”50”,”ecrule1”:”测试中1”,”ecrule2”:”“,”ecrule3”:”“,}