LocalDateTime 序列化格式错误

314 阅读1分钟
  • 问题描述:通过JsonFormat注解来实现时间的格式化
@JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime timestamp;
...
new ObjectMapper().writeValueAsString(obj);
  • 结果
  "timestamp": {
    "year": 2022,
    "month": "FEBRUARY",
    "nano": 326000000,
    "monthValue": 2,
    "dayOfMonth": 24,
    "hour": 11,
    "minute": 40,
    "second": 58,
    "dayOfWeek": "THURSDAY",
    "dayOfYear": 55,
    "chronology": {
      "calendarType": "iso8601",
      "id": "ISO"
    }
  • 解决办法: 增加@JsonSerialize注解
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime timestamp;