首页 > 解决方案 > How to send/receive a date object to be in a different format in JSON and not in timestamp?

问题描述

I have the following POJO which I use to send out as messages to rabbitmq:

public class MyMessage {
    private String id;
    private String name;
    private Date createdDt;

    @JsonCreator
    public MyMessage(
        @JsonProperty("id") String id,
        @JsonProperty("name") String name,
        @JsonProperty("createdDt") Date createdDt
    ) {
        this.id = id;
        this.name = name;
        this.createdDt = createdDt;
    }
}

The problem with this is that when I send it using rabbitTemplate.convertAndSend(), the createdDt will be in unix timestamp in the JSON message. I need the createdDt in the JSON after serialised to be in the format of dd-MM-yyyy HH:mm:ss.

I don't want to change the createdDt property in MyMessage class to be a string in that formatted date because I may want to use the POJO else where in the code and having the date as a string is not convenient later. It also doesn't sound "right" to have the date in string just for the purpose of having it in a particular format.

When I'm receiving the message back, I also need to deserialise that string date in the format of dd-MM-yyyy HH:mm:ss back into a Date object.

How can I keep the createdDt as a Date object while sending the date in a different format when serialised and then have the string deserialised back as a date object?

标签: javajsondateserializationjackson

解决方案


如果必须使用,则只需在字段中java.util.Date添加以下注释createdDt

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
private Date createdDt;

推荐阅读