java - Java Object Mapper 日期转换为 Json
问题描述
我正在使用 ObjectMapper 将对象列表转换为 JSON,但是日期字段转换为键值,请参见下面的当前输出
电流输出:
{"startDateTime": {"year":2021,"monthValue":8,"dayOfMonth":24,"hour":20,"minute":5,"second":56,"nano":0,"month":"AUGUST","dayOfWeek":"TUESDAY","dayOfYear":236,"chronology":{"id":"ISO","calendarType":"iso8601"}}
预期的输出是
{"startDateTime": "24-08-2021 17:56:16",
"endDateTime": "24-08-2021 17:57:00",
"userName": "Lakshman"}
我的代码:
ObjectMapper objectMapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
objectMapper.setDateFormat(df);
String jsonList = objectMapper.writeValueAsString(userList);
System.out.println("userlog =>> " + jsonList);
用户类
public class UserEventsEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@JsonIgnore
// @CreationTimestamp
@Column(name="start_date_time")
@JsonFormat(pattern="dd-MM-yyyy HH:mm:ss", timezone="Asia/Kolkata")
private LocalDateTime startDateTime;
@JsonIgnore
// @CreationTimestamp
@Column(name="end_date_time", nullable =true)
@JsonFormat(pattern="dd-MM-yyyy HH:mm:ss", timezone="Asia/Kolkata")
private LocalDateTime endDateTime;
@Column(length = 25, nullable = false)
private String userName;
@JsonFormat(pattern="dd-MM-yyyy HH:mm:ss", timezone="Asia/Kolkata")
public LocalDateTime getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(LocalDateTime startDateTime) {
this.startDateTime = startDateTime;
}
@JsonFormat(pattern="dd-MM-yyyy HH:mm:ss", timezone="Asia/Kolkata")
public LocalDateTime getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(LocalDateTime endDateTime) {
this.endDateTime = endDateTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
解决方案
通过注册 JavaTimeModule 问题得到解决
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
String jsonList = objectMapper.writeValueAsString(userList);
System.out.println("userlog =>> " + jsonList);
推荐阅读
- javascript - React Router redirect after submitting a form using the input value
- php - 从具有特定开始日期的随机顺序对天数数组进行排序
- ssl - SSL 终止后本地 kubernetes 后端服务地址的 HTTPS 端点
- kotlin - 将可迭代对象收集到一个变量(列表)中
- node.js - 测试网上总是出错:交易未在 750 秒内被挖掘
- excel - VBA提示“打开”对话框并选择要从中导入导入的目录
- java - Java Prepared 语句等于时间戳字段上的日期比较
- ag-grid - ag-grid 的 IHeaderComponent 中的 angularjs 指令?
- php - 如何在 for 循环中创建一个数组并在 forloop 之外访问该数组
- sql - sql中每个请求的sumTotal Duration