Arto Oksanen
Arto Oksanen

Reputation: 1

Format of java.sql.Timestamp in JSON has changed

When upgrading a rest service from JEE7 to jakarta.jakartaee-api (v 10.0.0) there is an unwanted change in format of java.sql.Timestamp timestamps. The timestamps used to be like this

{"timestamp": 1568281963809}

but now they are like this

{"timestamp": "2019-09-12T10:52:43.808Z[UTC]"}

In the java code the json response is generated simply like this:

return Response.ok(someDto).build();

The parameter someDto is a java object that has many fields including some Timestamps. The json is otherwise just fine, but the timestamps have this wrong string format. The clients that are calling the rest interface do not like the formatted string at all as they are expecting an integer value.

What is the best and easiest way to change the format back as it was? It should be the default?

Upvotes: 0

Views: 44

Answers (1)

Arto Oksanen
Arto Oksanen

Reputation: 1

I am answering my own question. It was almost solved by adding this:

JsonbConfig config = new JsonbConfig();
config.setProperty(JsonbConfig.DATE_FORMAT, JsonbDateFormat.TIME_IN_MILLIS);
Jsonb jsonB = JsonbBuilder.create(config);

and writing the response like this:

return Response.ok(jsonB.toJson(object)).build();

But as the objects can have also Date fields in addition to the Timestamps they are now both written as integers and now the clients dont like Date fields as they are expecting something like "2023-05-05".

For example:

public class HaePaivajarjestysPaluuDto extends SaliDtoAC implements Serializable {
    private String tekninenavain;
    private Date istuntopvm;
    private Timestamp ilmoitettualkuaika;

gives:

"haePaivajarjestysPaluuDto": {
  "tekninenavain": "2023/131",
  "ilmoitettualkuaika": 1683270000000,
  "istuntopvm": 1683234000000,

And the client fails with this error:

Caused by: java.text.ParseException: Unparseable date: "1683234000000"
        at java.text.DateFormat.parse(DateFormat.java:377) ~[?:1.8.0]
        at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:105) ~[gson-2.2.4.jar:?]

This was solved by adding @JsonbDateFormat annotation to those Date fields like this

@JsonbDateFormat("yyyy-MM-dd")
private Date istuntopvm;

And now finally everything works like in JEE7:

"haePaivajarjestysPaluuDto": {
  "tekninenavain": "2023/131",
  "ilmoitettualkuaika": 1683280800000,
  "istuntopvm": "2023-05-05",

Upvotes: 0

Related Questions