java - 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?
解决方案
如果必须使用,则只需在字段中java.util.Date
添加以下注释createdDt
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
private Date createdDt;
推荐阅读
- python - Setting up multiple iterative statement
- sqlalchemy - 如何在金字塔应用程序启动时从数据库中读取表?
- excel - 从 Excel 自动完成 Word Doc
- python - 向 Python 开发人员提出的问题:您是否在 setup.py 中冻结了所有包版本?
- r - 我的函数中的循环不会更改我的数据类型(在 R 中)
- javascript - Ionic 4 Stripe.js 集成
- android - android.database.sqlite.SQLiteException:华为设备上没有这样的表错误
- c# - 如何在asp.net核心中调用c#方法的ajax获取当前主机名和路径名
- reactjs - 能
- c# - .Include() 未返回 Entity Framework Core 3.1.2 相关数据