Java json response shows date in numeric value

有些话、适合烂在心里 提交于 2020-08-20 11:47:27

问题


@Data
public class Reponse {

    private String event;

    @Temporal(TemporalType.TIMESTAMP)
    private Date eventDate;

    private Double amount;
}

Json response is like

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

Here, eventDate is showing numeric value 1540317600000 instead of 2018-10-23


回答1:


You can annotated the field with @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm"). Then, response time format will be like "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;
}



回答2:


If you use Spring boot 2.x instead 1.x ,the default behavior has changed
add spring.jackson.serialization.write-dates-as-timestamps=true to your configuration to return to the previous behavior
Spring Boot 2.0 Migration Guide




回答3:


spring 2.x flipped a Jackson configuration default to write JSR-310 dates as ISO-8601 strings. If you wish to return to the previous behavior, you can add

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

to your application-context configuration file.




回答4:


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);


来源:https://stackoverflow.com/questions/52964744/java-json-response-shows-date-in-numeric-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!