SpringBoot+MyBatis Plus对Map中Date格式转换的处理( 二 )


  1. public final void defaultSerializeDateValue(long timestamp, JsonGenerator gen) throws IOException {

  2. if (this.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {

  3. gen.writeNumber(timestamp);

  4. } else {

  5. gen.writeString(this._dateFormat().format(new Date(timestamp)));

  6. }

  7. }

  8. public final void defaultSerializeDateValue(Date date, JsonGenerator gen) throws IOException {

  9. if (this.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {

  10. gen.writeNumber(date.getTime());

  11. } else {

  12. gen.writeString(this._dateFormat().format(date));

  13. }

  14. }

解决局部方案1. 字段注解这种方式可以用在固定的类成员变量上, 不改变整体行为
  1. public class Event {

  2.    public String name;

  3.    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")

  4.    public Date eventDate;

  5. }

另外还可以自定义序列化反序列化方法, 实现 StdSerializer
  1. public class CustomDateSerializer extends StdSerializer<Date> {

  2.    //...

  3. }

就可以在 @JsonSerialize 注解中使用
  1. public class Event {

  2.    public String name;

  3.    @JsonSerialize(using = CustomDateSerializer.class)

  4.    public Date eventDate;

  5. }

2. 修改 ObjectMapper通过 ObjectMapper.setDateFormat() 设置日期格式, 改变默认的日期序列化反序列化行为. 这种方式只对调用此ObjectMapper的场景有效
  1. private static ObjectMapper createObjectMapper() {

  2. ObjectMapper objectMapper = new ObjectMapper();

  3. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  4. objectMapper.setDateFormat(df);

  5. return objectMapper;

  6. }

因为 ObjectMapper 一般是当作线程安全使用的, 而 SimpleDateFormat 并非线程安全, 在这里使用是否会有问题? 关于这个疑虑, 可以查看 这个链接
@StaxMan: I am a bit concerned if ObjectMapper is still thread-safe after ObjectMapper#setDateFormat() is called. It is known that SimpleDateFormat is not thread safe, thus ObjectMapper won't be unless it clones e.g. SerializationConfig before each writeValue() (I doubt). Could you debunk my fear? – dma_k Aug 2, 2013 at 12:09
DateFormat is indeed cloned under the hood. Good suspicion there, but you are covered. – StaxMan Aug 2, 2013 at 19:43

推荐阅读