0

I'm trying to serialize a Timestamp Object to a JSON. But the object in the JSON is displayed as seconds.

This is a snippet of my POJO:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class TimeAndDateDetail{

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh.mm.ss")
    private Timestamp timeAndDate;

    public Timestame getTimeAndDate() {return timeAndDate; }

    public void setTimeAndDate(Timestamp timeAndDate){
        this.timeAndDate = timeAndDate;
    }
}

This is my output:

{
    "timeAndDate": 1583038800000
}

Why is this happening? And how can I get it to keep its original format?

Brodiman
  • 149
  • 2
  • 9
  • What is 'the original format'? A `java.sql.Timestamp` doesn't really have a format unless you mean its `toString()` implementation, which is relative to the JVM default time zone on your machine. – Mark Rotteveel Feb 27 '20 at 16:21
  • "yyyy-MM-dd hh:mm:ss" is the original format before it is serialized. – Brodiman Feb 27 '20 at 17:09

2 Answers2

1

You can annotate the field with @JsonFormat to specify the format, that the timestamp will be serialized. Here is an example:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm")
Andronicus
  • 25,419
  • 17
  • 47
  • 88
0

Looks like you are using jackson, and this is the default behaviour of it. best way is to disable the related object mapper feature:

objectMapper
    .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
Kemal Cengiz
  • 133
  • 1
  • 8
  • Do I add this line to my main Class or a POJO? Compiler is complaining that it can't resolve this. – Brodiman Feb 27 '20 at 21:16
  • are you using jackson? if yes, you should add this line wherever you create the object mapper – Kemal Cengiz Feb 28 '20 at 10:11
  • if you are using spring for example, then check this answer to find how to inject object mapper: https://stackoverflow.com/a/32842962/10668681 – Kemal Cengiz Feb 28 '20 at 10:12
  • I'm not creating an ObjectMapper. I'm using the Produces annotation and letting the system handle that. Can I still throw this line in there somewhere? – Brodiman Feb 28 '20 at 13:48
  • what is your framework? can this question be relevant: https://stackoverflow.com/questions/18872931/custom-objectmapper-with-jersey-2-2-and-jackson-2-1 – Kemal Cengiz Feb 28 '20 at 17:06