2023-05-24 17:18:18
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
@Configuration
public class JacksonConfig {

@Bean
public ObjectMapper objectMapper() {

ObjectMapper objectMapper = new ObjectMapper()
// 设置序列化反序列化采用直接处理字段的方式, 不依赖setter 和 getter
.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
// 反序列化设置 关闭反序列化时Jackson发现无法找到对应的对象字段,便会抛出UnrecognizedPropertyException: Unrecognized field xxx异常
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
// 序列化设置 时间戳
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);

SimpleModule simpleModule = new SimpleModule();
simpleModule.addDeserializer(Date.class, new MyJsonDeserializer());
simpleModule.addSerializer(Date.class, new MyJsonSerializer());
// objectMapper.registerModule(simpleModule); 如果前后端不通过时间戳交互,使用该处理器
return objectMapper;
}

/**
* 自定义反序列化处理器
* 支持yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
*/
public static class MyJsonDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String source = p.getText().trim();
try {
return DateUtil.parse(source);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

/**
* 自定义序列化处理器
*/
@NoArgsConstructor
@AllArgsConstructor
public static class MyJsonSerializer extends JsonSerializer<Date> implements ContextualSerializer {
private JsonFormat jsonFormat;

/**
* 默认序列化yyyy-MM-dd HH:mm:ss
* 若存在@JsonFormat(pattern = "xxx") 则根据具体其表达式序列化
*/
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value == null) {
gen.writeNull();
return;
}
String pattern = jsonFormat == null ? DatePattern.NORM_DATETIME_PATTERN : jsonFormat.pattern();
gen.writeString(DateUtil.format(value, pattern));
}

/**
* 通过字段已知的上下文信息定制 JsonSerializer
* 若字段上存在@JsonFormat(pattern = "xxx") 则根据上面的表达式进行序列化
*/
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
JsonFormat ann = property.getAnnotation(JsonFormat.class);
if (ann != null) {
return new MyJsonSerializer(ann);
}
return this;
}
}


}

如果使用了时间戳来交互,当个别接口想使用yyyy-HH-dd格式的时候,在字段上指定

1
2
@JsonFormat(pattern = "yyyy-MM-dd HH", timezone = "GMT+8")
private Date createTime;

关于时区的问题

我也可以直接存中国时间呀,如果用户是日本的,我只需要计算下中国和日本的时间差就可以。

使用datetime存UTC时间,然后根据用户时区来转换。时区可以让用户填写或者根据ip判断

Prev
2023-05-24 17:18:18
Next