Java json 响应以数值形式显示日期

Java json response shows date in numeric value

@Data
public class Reponse {

    private String event;

    @Temporal(TemporalType.TIMESTAMP)
    private Date eventDate;

    private Double amount;
}

Json 回复就像

{ 
  event: "transcation',
  eventDate: 1213123434,
  amount: 100
}

这里,eventDate 显示数值 1540317600000 而不是 2018-10-23

I suppose you are using rest framework such as spring boot or jersey which in turn 
converts your java date into epoch format before sending it to the client. So while 
sending response you can format you date into the format you want. Please refer 
the code below.

import java.text.SimpleDateFormat;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
sdf.setLenient(false);
String responseDate = sdf.format(date);

如果您使用 Spring 引导 2.x 而不是 1.x,则默认行为已更改
spring.jackson.serialization.write-dates-as-timestamps=true 添加到您的配置到 return 到以前的行为
Spring Boot 2.0 Migration Guide

您可以用 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm") 注释该字段。然后,响应时间格式将类似于“yyyy-MM-dd HH:mm

import com.fasterxml.jackson.annotation.JsonFormat;


public class Reponse {

    private String event;

    @Temporal(TemporalType.TIMESTAMP)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm")
    private Date eventDate;

    private Double amount;
}

spring 2.x 翻转了 Jackson 配置默认值,将 JSR-310 日期写入 ISO-8601 字符串。如果你想 return 到以前的行为,你可以添加

spring.jackson.serialization.write-dates-as-timestamps=true 

到您的 application-context 配置文件。