弹簧自动将OffsetDateTime序列化为时间戳

时间:2019-03-26 12:40:22

标签: spring datetime serialization java-8

我有一组春季微服务,并且大多数回复都包含timestamp字段

@NotNull
public OffsetDateTime timestamp = OffsetDateTime.now(ZoneOffset.UTC);

此属性序列化为

  "timestamp": {
    "offset": {
      "totalSeconds": 0,
      "id": "Z",
      "rules": {
        "transitionRules": [],
        "transitions": [],
        "fixedOffset": true
      }
    },
    "nano": 998000000,
    "year": 2019,
    "dayOfWeek": "TUESDAY",
    "hour": 12,
    "month": "MARCH",
    "dayOfMonth": 26,
    "dayOfYear": 85,
    "minute": 20,
    "monthValue": 3,
    "second": 33
  },

有什么方法可以配置Spring以将其序列化为常规的timeStamp对象  2015-10-20T11:00:00-8:30

1 个答案:

答案 0 :(得分:0)

您可以实现以下序列化器:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class OffsetDateTimeSerializer extends StdSerializer<OffsetDateTime> {
    public OffsetDateTimeSerializer() {
        super(OffsetDateTime.class);
    }

    @Override
    public void serialize(final OffsetDateTime dateTime, final JsonGenerator generator,
                          final SerializerProvider provider) throws IOException {
        generator.writeString(dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
    }
}

并使用以下注释您的字段:

@JsonSerialize(using = OffsetDateTimeSerializer.class)