Date and Timestamp serialization by Jackson ObjectMapper

Viewed 5524

Jackson ObjectMapper is serializing both Date and Timestamp as Long in 2.9.x version whereas Date is serialized as Formatted String in 2.6.x and Timestamp as Long in **2.6.x* version by default.

Example:

case class Test(date: java.sql.Date,  tmp: java.sql.Timestamp)
val test = Test(new java.sql.Date(1588892400000L), new Timestamp(1588892400000L))
writeValueAsString(test)
{"date":"2020-05-08","tmp":1588892400000}//Version 2.6.x 
{"date":1588892400000,"tmp":1588892400000}//Version 2.9.x

But I want to maintain the behavior of 2.6.x version in 2.9.x version.

I tried disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) but then it is converting both Date & TimeStamp to Formatted String (as below).

{"date":"2020-05-08","tmp":"2020-05-07T23:00:00.000+0000"}

If I set DateFormatter**, then it converts both in the same format.

setDateFormat(new SimpleDateFormat("yyyy-MM-dd"))`
{"date":"2020-05-08","tmp":"2020-05-08"}

**I just treid it but I don't want to set DateFormatter (even if it works) because it will be used for de-serialization too where the input date format is different.

Is there a way to achieve this?

1 Answers

You can use an annotation like this for the Date member:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")

EDIT:

Create a class like this:

public class CustomSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
            String s = sdf.format(value);
            gen.writeString(s);
          } catch (DateTimeParseException e) {
            System.err.println(e);
            gen.writeString("");
          }     
    }
}

and use like this:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Date.class, new CustomSerializer());
mapper.registerModule(module);
Related