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
|
package com.sdstc.pdm.common.codec;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
public class LocalDateTimeCodec implements ObjectSerializer, ObjectDeserializer {
@Override
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
if (type != LocalDateTime.class) {
throw new RuntimeException("Wrong Type");
}
Long timestamp = Long.valueOf((String) parser.parse());
//noinspection unchecked
return (T) LocalDateTime.ofEpochSecond(
timestamp / 1000, 0, ZoneOffset.ofHours(8));
}
@Override
public int getFastMatchToken() {
return 0;
}
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
if (!(object instanceof LocalDateTime)) {
throw new RuntimeException("Wrong Type");
}
LocalDateTime time = (LocalDateTime) object;
serializer.write(time.toInstant(ZoneOffset.of("+8")).toEpochMilli());
}
}
|