gson日期类型字段序列化与反序列化

为了避免日期格式转换的问题,在序列化日期类型字段时为Long类型,反序列化为Date类型。

代码如下:

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
@Slf4j
public class GsonDateTest {
private static GsonBuilder builder = new GsonBuilder();
private static Gson gson;
static {
// 将日期序列化为Long类型
builder.registerTypeAdapter(java.util.Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> new JsonPrimitive(date.getTime()))
// 将Long类型转换为Date
.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()));
gson = builder.create();
}

public String toJson(Match match) {
return gson.toJson(match);
}

public static void main(String[] args) {
GsonDateTest test = new GsonDateTest();
Match match = Match.builder().id(1).name("name 2").build();
Date date = new Date();
match.setMatchTime(date);
match.setMatchTimeMs(date.getTime());
String jsonStr = test.toJson(match);
log.info("jsonStr:{}",jsonStr);
match = gson.fromJson(jsonStr,new TypeToken<Match>(){}.getType());
log.info("match:{}",match);

jsonStr = "{\"msgType\":\"season\",\"data\":[{\"sportId\":1,\"pstatus\":0,\"year\":\"2019-2020\",\"tournamentId\":99,\"start\":1563580800000,\"end\":1590883140000,\"ptype\":0,\"id\":11132,\"source\":\"tyson\"}]}";
Type type = new TypeToken<BaseData<SSeason>>(){}.getType();
BaseData<SSeason> sSeason = gson.fromJson(jsonStr,type);
log.info("season:{}",sSeason);
}
}

结果:

1569827079208

Donny wechat
欢迎关注我的个人公众号
打赏,是超越赞的一种表达。
Show comments from Gitment