Administrator
2021-11-09 5f50bd6ea5d5bdb7b8ea4d9e9a5851067b9aec1b
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */
package com.duqing.missions.util;
 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
 
/**
 * Json工具类.
 */
public class GsonUtils {
    private static Gson gson = new GsonBuilder().create();
 
    public static String toJson(Object value) {
        return gson.toJson(value);
    }
 
    public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
        return gson.fromJson(json, classOfT);
    }
 
    public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
        return (T) gson.fromJson(json, typeOfT);
    }
 
    /**
     * 将对象转换为驼峰命名的json
     * @param value
     * @return
     */
    public static String toHumpJson(Object value) {
        try {
            if(value instanceof Collection){
                    return convertToHumpJsonArray(new JSONArray(gson.toJson(value)) ).toString();
            }else {
                return convertToHumpJsonObj(new JSONObject(gson.toJson(value)) ).toString();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return gson.toJson(value);
        }
    }
 
    /**
     *
     * 将json转换为驼峰命名的json
     * @param json
     * @return
     */
    public static String toHumpJson(String json) throws JSONException {
        if(json.indexOf("[") == 0){
            return convertToHumpJsonArray(new JSONArray(json) ).toString();
        }else {
            return convertToHumpJsonObj(new JSONObject(json) ).toString();
        }
    }
 
    /**
     * 驼峰命名转换
     * @param json
     * @param classOfT
     * @param <T>
     * @return
     * @throws JsonParseException
     */
    public static <T> T fromJsonToHump(String json, Class<T> classOfT) throws JsonParseException, JSONException {
        return  gson.fromJson(toHumpJson(json), classOfT);
    }
 
    /**
     * 驼峰命名转换
     * @param json
     * @param typeOfT
     * @param <T>
     * @return
     * @throws JsonParseException
     */
    public static <T> T fromJsonToHump(String json, Type typeOfT) throws JsonParseException, JSONException {
        return (T) gson.fromJson(toHumpJson(json), typeOfT);
    }
 
    /**
     * 转换驼峰命名
     * @param jsonObject
     * @return
     */
    public static JSONObject convertToHumpJsonObj(JSONObject jsonObject){
        JSONObject temp = new JSONObject();
        Iterator<String> it = jsonObject.keys();
        while ( it.hasNext()){
            String key = it.next();
            String humpKey = humpName(key);
            try {
                if(jsonObject.get(key) instanceof JSONObject){
                    temp.put(humpKey,convertToHumpJsonObj(jsonObject.getJSONObject(key)));
                }else if(jsonObject.get(key) instanceof JSONArray){
                    temp.put(humpKey,convertToHumpJsonArray(jsonObject.getJSONArray(key)));
                }else {
                    temp.put(humpKey,jsonObject.get(key));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return temp;
 
    }
 
    public static JSONArray convertToHumpJsonArray(JSONArray array){
        JSONArray jsons = new JSONArray();
        for(int i = 0 ; i < array.length() ; i ++){
            try {
                if(array.get(i) instanceof JSONObject){
                    jsons.put(convertToHumpJsonObj(array.getJSONObject(i)));
                }else if(array.get(i) instanceof JSONArray){
                    jsons.put(convertToHumpJsonArray(array.getJSONArray(i)));
                }else {
                    jsons.put(array.get(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsons;
 
    }
    /**
     * 将key转换为驼峰
     * @param param
     * @return
     */
    public static Map convertToHumpMap(Map<String, Object> param){
        Map temp = new TreeMap();
        for(String key: param.keySet()){
            String humpKey = humpName(key);
            if(param.get(key) instanceof Map){
                temp.put(humpKey,convertToHumpMap((Map<String, Object>) param.get(key)));
            }else if(param.get(key) instanceof List){
                temp.put(humpKey,convertToHumpList((List)param.get(key)));
            }else {
                temp.put(humpKey,param.get(key));
            }
        }
        return temp;
    }
 
 
    public static List convertToHumpList(List list){
        List ars = new ArrayList();
        for(Object object : list){
            if(object instanceof Map){
                ars.add(convertToHumpMap((Map)object));
            }else if(object instanceof List){
                ars.add(convertToHumpList((List)object));
            }else {
                ars.add(object);
            }
        }
        return ars;
    }
    /**
     * 驼峰命名
     * @param name
     * @return
     */
    public static String humpName(String name){
        String[] strings = name.split("_");
        StringBuilder sb = new StringBuilder();
        sb.append(strings[0]);
        for(int i = 1 ; i < strings.length ; i ++){
            sb.append(toUperFirst(strings[i]));
        }
        if(sb.toString().equals("new")){//关键字 转成大写
            return "NEW";
        }
        return sb.toString();
    }
 
    /**
     * 首字母大写
     * @param name
     * @return
     */
    public static String toUperFirst(String name){
        return name.substring(0,1).toUpperCase()+name.substring(1);
    }
 
    /**
     * json字符串缩进
     * @param json
     * @return
     */
    public static String retractJson(String json){
        int level = 0 ;
        StringBuffer jsonForMatStr = new StringBuffer();
        for(int index=0;index<json.length();index++)//将字符串中的字符逐个按行输出
        {
            //获取s中的每个字符
            char c = json.charAt(index);
            //          System.out.println(s.charAt(index));
 
            //level大于0并且jsonForMatStr中的最后一个字符为\n,jsonForMatStr加入\t
            if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
                jsonForMatStr.append(getLevelStr(level));
                //                System.out.println("123"+jsonForMatStr);
            }
            //遇到"{"和"["要增加空格和换行,遇到"}"和"]"要减少空格,以对应,遇到","要换行
            switch (c) {
                case '{':
                case '[':
                    jsonForMatStr.append(c + "\n");
                    level++;
                    break;
                case ',':
                    if(index>0 && index < json.length()-2 && (json.charAt(index-1) != '\n') && json.charAt(index+1) == '"'){
                        jsonForMatStr.append(c + "\n");
                    }else{
                        jsonForMatStr.append(c);
                    }
                    break;
                case '}':
                case ']':
                    jsonForMatStr.append("\n");
                    level--;
                    jsonForMatStr.append(getLevelStr(level));
                    jsonForMatStr.append(c);
                    break;
                default:
                    jsonForMatStr.append(c);
                    break;
            }
        }
        return jsonForMatStr.toString();
    }
    private static String getLevelStr(int level) {
        StringBuffer levelStr = new StringBuffer();
        for (int levelI = 0; levelI < level; levelI++) {
            levelStr.append("\t");//\t或空格
        }
        return levelStr.toString();
    }
}