1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| package com.tiantai.policys.commons.utils.common;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.*;
public class JSONObjectUtil {
public static JSONObject humpConvertJSONObject(JSONObject json) { if (null == json) { return null; } Set<String> keys = json.keySet(); String[] array = keys.toArray(new String[0]); for (String key : array) { Object value = json.get(key); String[] keyArray = key.toLowerCase().split("_"); if (isUpperCase(key) && !key.contains("_")) { json.remove(key); json.put(key.toLowerCase(), value); continue; } if (keyArray.length > 1) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < keyArray.length; i++) { String ks = keyArray[i]; if (!"".equals(ks)) { if (i == 0) { sb.append(ks); } else { int c = ks.charAt(0); if (c >= 97 && c <= 122) { int v = c - 32; sb.append((char) v); if (ks.length() > 1) { sb.append(ks.substring(1)); } } else { sb.append(ks); } } } } json.remove(key); json.put(sb.toString(), value); } } return json; }
public static List<JSONObject> humpConvertListObject(List<JSONObject> objectList) { if (null == objectList || objectList.size() <= 0) { return null; } List<JSONObject> data = new ArrayList<>(); for (JSONObject object : objectList) { data.add(humpConvertJSONObject(object)); } return data; }
public static List<JSONObject> humpConvertJSONArray(JSONArray array) { if (null == array || array.size() <= 0) { return null; } List<JSONObject> data = new ArrayList<>(); for (int i = 0; i < array.size(); i++) { data.add(humpConvertJSONObject(array.getJSONObject(i))); } return data; }
public static boolean isUpperCase(String str) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= 97 && c <= 122) { return false; } } return true; } public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); jsonObject.put("QWE_QWE1","1"); jsonObject.put("qwe_qwe2","2"); jsonObject.put("qwe_Qwe3","3"); jsonObject.put("QWEQWE4","4"); jsonObject.put("qweqwe5","5"); jsonObject.put("qweQwe6","6"); System.out.println(humpConvertJSONObject(jsonObject)); } }
|