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!
-
1basically you want to convert java timestamp to formatted string which goes in as a value for one of your json property. right ?satish chennupati– satish chennupati2016-11-23 20:47:38 +00:00Commented Nov 23, 2016 at 20:47
-
1did you try formatting the Date object???ΦXocę 웃 Пepeúpa ツ– ΦXocę 웃 Пepeúpa ツ2016-11-23 20:49:34 +00:00Commented Nov 23, 2016 at 20:49
-
The problem is that I using automatical mechanisms of spring - something like ResponseBody (jackson and other similar stories)user6023611– user60236112016-11-23 20:51:10 +00:00Commented Nov 23, 2016 at 20:51
-
even if you use spring request body you can still extract the date, format and set it back.satish chennupati– satish chennupati2016-11-23 20:57:23 +00:00Commented Nov 23, 2016 at 20:57
-
Can you be more precisely ? Set it back on sq.Timestamp type after format ? Seems to be harduser6023611– user60236112016-11-23 21:37:42 +00:00Commented Nov 23, 2016 at 21:37
3 Answers
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.
Comments
@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
Comments
convert your timestamp using the following format
SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
a sample code will be :
Timestamp ts = new Timestamp(new Date().getTime());
System.out.println(ts);
SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
System.out.println(sdf.format(ts));
will print out
2016-11-23 15:55:22.291
Wed, 23 Nov 2016 15:55:22 EST