Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 1105

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 response is like

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

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

Upvotes: 0

Views: 7962

Answers (4)

Pravin Bansal
Pravin Bansal

Reputation: 4681

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.

Upvotes: 1

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 1105

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

Upvotes: 8

zujool
zujool

Reputation: 41

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

Upvotes: 3

kashish verma
kashish verma

Reputation: 61

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

Upvotes: 0

Related Questions