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() .setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE) .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) .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());
return objectMapper; }
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;
@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)); }
@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判断