![](/img/trans.png)
[英]Object Mapper convert json format to object, java
[英]Java Object Mapper date conversion to Json
我正在使用 ObjectMapper 将对象列表转换为 JSON,但是日期字段转换为键值,请参见下面的当前 output
当前 output:
{"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"}}
Output 预计是
{"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);
用户 Class
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.