admin
2019-09-26 c33c46549b12a674ccabb175c6b0632551780fdd
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package org.yeshi.utils;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
 
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
 
public class JsonUtil {
 
    static Gson baseGson = new Gson();
 
    public static String loadTrueResult(Object result) {
        JSONObject object = new JSONObject();
        object.put("code", 0);
        object.put("data", result);
        return object.toString();
 
    }
 
    public static String loadFalseResult(String error) {
        JSONObject object = new JSONObject();
        object.put("code", 1);
        object.put("msg", error);
        return object.toString();
    }
 
    public static String loadTrueResult(int code, Object result) {
        JSONObject object = new JSONObject();
        object.put("code", code);
        object.put("data", result);
        System.out.println(object.toString());
        return object.toString();
    }
 
    public static JSONObject loadTrue(int code, Object data, String msg) {
        JSONObject object = new JSONObject();
        object.put("code", code);
        object.put("data", data);
        object.put("msg", msg);
        System.out.println(object.toString());
        return object;
    }
 
    public static String loadJSONP(String callback, String data) {
        return callback + "(" + data + ")";
    }
 
    public static String loadFalseResult(int code, String error) {
        JSONObject object = new JSONObject();
        object.put("code", code);
        object.put("msg", error);
        return object.toString();
    }
 
    // 返回方式
    public static void printMode(PrintWriter out, String callback, String JsonData) {
        if (StringUtil.isNullOrEmpty(callback)) {
            out.print(JsonData);
        } else {
            out.print(JsonUtil.loadJSONP(callback, JsonData));
        }
    }
 
    public static JSONObject getJSONObject(Object obj) {
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().excludeFieldsWithoutExposeAnnotation()
                .setDateFormat(DateFormat.LONG).setPrettyPrinting().setVersion(1.0).create();
        return JSONObject.fromObject(gson.toJson(obj));
    }
 
    public static Gson getGson() {
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().excludeFieldsWithoutExposeAnnotation()
                .setDateFormat(DateFormat.LONG).setPrettyPrinting().setVersion(1.0).create();
        return gson;
    }
 
    public static Gson getSimpleGson() {
        return new GsonBuilder().create();
    }
 
    public static Gson getSimpleGsonWithDate() {
        GsonBuilder gb = new GsonBuilder();
        gb.registerTypeAdapter(java.util.Date.class, new JsonSerializer<Date>() {
 
            public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
                return new JsonPrimitive(arg0.getTime());
            }
 
        }).setDateFormat(DateFormat.LONG);
        Gson gson = gb.create();
        return gson;
    }
 
    public static Gson getSimpleGsonWithDateAndSerialization() {
        GsonBuilder gb = new GsonBuilder();
        gb.registerTypeAdapter(java.util.Date.class, new JsonSerializer<Date>() {
 
            public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
                return new JsonPrimitive(arg0.getTime());
            }
 
        }).setDateFormat(DateFormat.LONG);
        gb.excludeFieldsWithoutExposeAnnotation();
 
        Gson gson = gb.create();
        return gson;
    }
 
    public static Map<String, String> parseData(String data) {
        GsonBuilder gb = new GsonBuilder();
        Gson g = gb.create();
        Map<String, String> map = g.fromJson(data, new TypeToken<Map<String, String>>() {
        }.getType());
        return map;
    }
 
    // 将BigDecimal转为字符串
    public static GsonBuilder getConvertBigDecimalToStringBuilder(GsonBuilder builder) {
        return builder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
            @Override
            public JsonElement serialize(BigDecimal value, Type theType, JsonSerializationContext context) {
                if (value == null) {
                    return new JsonPrimitive("");
                } else {
                    return new JsonPrimitive(value.toString());
                }
            }
        });
    }
 
    /**
     * 获取客户端接口常用的gson
     * 
     * @return
     */
    public static Gson getApiCommonGson() {
        GsonBuilder gsonBuilder = getConvertBigDecimalToStringSubZeroBuilder(new GsonBuilder());
        gsonBuilder.excludeFieldsWithoutExposeAnnotation();
        return gsonBuilder.create();
    }
 
    public static GsonBuilder getConvertBigDecimalToStringSubZeroBuilder(GsonBuilder builder) {
        return builder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
            @Override
            public JsonElement serialize(BigDecimal value, Type theType, JsonSerializationContext context) {
                if (value == null) {
                    return new JsonPrimitive("");
                } else {
                    return new JsonPrimitive(BigDecimalUtil.getWithNoZera(value).toString());
                }
            }
        });
    }
 
    // 将日期转为几天前这种形式
    public static GsonBuilder getConvertDateToShortNameBuilder(GsonBuilder builder) {
        return builder.registerTypeAdapter(Date.class, new TypeAdapter<Date>() {
 
            @Override
            public void write(JsonWriter out, Date value) throws IOException {
                String desc = "";
                if (value != null) {
                    // 判断是否是同一天
                    long old = value.getTime();
                    long now = System.currentTimeMillis();
                    long oldDay = old / (1000 * 60 * 60 * 24L);
                    long nowDay = now / (1000 * 60 * 60 * 24L);
                    if (oldDay == nowDay) {// 同一天
                        long cha = now - old;
                        if (cha < 1000 * 60 * 2L)
                            desc = "刚刚";
                        else if (cha < 1000 * 60 * 60L)
                            desc = (cha / (1000 * 60)) + "分钟前";
                        else
                            desc = (cha / (1000 * 60 * 60)) + "小时前";
                    } else if (nowDay - oldDay == 1) {
                        desc = "昨天";
                    } else {
                        desc = (nowDay - oldDay) + "天前";
                    }
                    out.value(desc);
                }
            }
 
            @Override
            public Date read(JsonReader in) throws IOException {
                return new Date();
            }
        });
 
    }
 
    public static Map<String, Object> parseData(JSONObject data) {
        Map<String, Object> map = new HashMap<String, Object>();
        Set<String> keySet = data.keySet();
        for (String key : keySet) {
            map.put(key, data.get(key));
        }
        return map;
    }
 
    /**
     * 将对象转换成json字符串。
     * <p>
     * Title: pojoToJson
     * </p>
     * <p>
     * Description:
     * </p>
     * 
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
        String string = baseGson.toJson(data);
        return string;
    }
 
    /**
     * 将json结果集转化为对象
     * 
     * @param jsonData
     *            json数据
     * @param clazz
     *            对象中的object类型
     * @return
     */
    public static <T> T jsonToObject(String jsonData, Class<T> beanType) {
        return baseGson.fromJson(jsonData, beanType);
    }
 
    /**
     * 将json数据转换成pojo对象list
     * <p>
     * Title: jsonToList
     * </p>
     * <p>
     * Description:
     * </p>
     * 
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
        if (StringUtil.isNullOrEmpty(jsonData))
            return null;
        List<T> list = new ArrayList<>();
        JSONArray array = JSONArray.fromObject(jsonData);
        for (int i = 0; i < array.size(); i++) {
            try {
                list.add(baseGson.fromJson(array.optJSONObject(i).toString(), beanType));
            } catch (Exception e) {
                list.add(baseGson.fromJson(array.optString(i), beanType));
            }
        }
        return list;
    }
 
}