-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathJSONTools.java
executable file
·91 lines (79 loc) · 2.58 KB
/
JSONTools.java
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
package com.luckin.stock.utils;
import java.text.DateFormat;
import java.util.Date;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
/**
*
* 说明:JSON管理
*
*
* @date 2015年3月25日
*
*/
public class JSONTools {
private static GsonBuilder gb = new GsonBuilder();
private static Gson gson = null;
static{
gb.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);
gb.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG);
gb.disableHtmlEscaping().serializeNulls();//.setPrettyPrinting()格式化
gson = gb.create();
}
public static Gson getGsonInstance(){
return gson;
}
public static String toGsonString(Object obj) {
return gson.toJson(obj);
}
public static String toGsonString(String[] excludeNames,Object obj){
Gson gson = gb.setExclusionStrategies(new JSONKit(excludeNames)).create();
return gson.toJson(obj);
}
public static Object parseGSONObject(String jsonString,Class<?> clazz){
return gson.fromJson(jsonString,clazz);
}
}
class DateSerializer implements JsonSerializer<Date> {
public JsonElement serialize(Date src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getTime());
}
}
class DateDeserializer implements JsonDeserializer<java.util.Date> {
public Date deserialize(JsonElement json, java.lang.reflect.Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
}
}
/**
* Gson序列化对象排除属性
* 调用方法: String[] keys = { "id" };
* Gson gson = new GsonBuilder().setExclusionStrategies(new JsonKit(keys)).create();
*/
class JSONKit implements ExclusionStrategy {
String[] keys;
public JSONKit(String[] keys) {
this.keys = keys;
}
@Override
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
@Override
public boolean shouldSkipField(FieldAttributes arg0) {
for (String key : keys) {
if (key.equals(arg0.getName())) {
return true;
}
}
return false;
}
}