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



  • }

  • 默认的序列化反序列化选项, 使用了一个常量 WRITE_DATES_AS_TIMESTAMPS, 在类 SerializationConfig 中进行判断, 未指定时使用的是时间戳
    1. public SerializationConfig with(DateFormat df) {

    2. SerializationConfig cfg = (SerializationConfig)super.with(df);

    3. return df == null ? cfg.with(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) : cfg.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    4. }

    实际的转换工作在 SerializerProvider 类中, 转换方法为
    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 注解中使用

      经验总结扩展阅读