Radoslav Ivanov
Radoslav Ivanov

Reputation: 1072

How to create a JsonbCong that writes Date in Number instead of String?

Obviously, with Eclipse Yasson JsonbDateFormat.TIME_IN_MILLIS annotation returns the date number as string:

 import javax.json.bind.annotation.JsonbDateFormat;

 class MyObject { 
    @JsonbDateFormat(JsonbDateFormat.TIME_IN_MILLIS)
    Date myDate;
 }

e.g outputs (quoted number)

{"myDate":"1234567890"}

How can I configure the json-b to omit the quotes around the number (like default behavior with Jackson)?, e.g.:

{"myDate":1234567890}

Upvotes: 2

Views: 856

Answers (1)

Ahmad Shahwan
Ahmad Shahwan

Reputation: 1968

Try a binding adapter from Date to Long (and vise-versa).

public static class DateAdapter implements JsonbAdapter<Date, Long> {

    @Override
    public Long adaptToJson(Date date) {
        return date.getTime();
    }

    @Override
    public Date adaptFromJson(Long ms) {
        return new Date(ms);
    }
}

Next, annotate the property with @JsonbTypeAdapter.

class MyObject { 
    @JsonbTypeAdapter(DateAdapter.class)
    Date myDate;
}

Upvotes: 1

Related Questions