I have a
private java.sql.Timestamp myDate;
In some model (POJO) class. Is it possible to convert it (by jackson) to something like that:
Wed, 23 Nov 2016 20:37:09 GMT
?
I know that I may use something like @JsonProperty
, however I can't deal with format of this one. Moreover, keep in mind that I not only send JSON, but also receive the same JSON.
Thank in advance!
You can add a custom serializer for your timestamp field.
public class JsonDateSerializer extends JsonSerializer<Timestamp> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
@Override
public void serialize(Timestamp arg0, JsonGenerator arg1, SerializerProvider arg2)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(arg0);
arg1.writeString(formattedDate);
}
}
Than add @JsonSerialize on your variable in POJO,
@JsonSerialize(using = JsonDateSerializer.class)
public Timestamp timestamp;
After that when you serializes it like this:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(//YOUR OBJECT HERE//);
You will get something like this :
{"timestamp":"Tue, 6 Dec 2016 19:06:33 IST"}
And it will deserialize back this passed JSON to your timestamp field in your POJO.
@JsonFormat annotation as follows, can be used on POJO java.sql.Timestamp members:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "E, dd MMM yyyy HH:mm:ss z", timezone = "GMT+2")
For MySQL TIMESTAMP record:
2018-04-30 14:10:13
Output is:
Mon, 30 Apr 2018 14:10:13 GMT+02:00
NOTE: This applies to Jackson 2.0 or newer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With