首页 > 解决方案 > 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;
    }

}

标签: javadate

解决方案


通过注册 JavaTimeModule 问题得到解决

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
String jsonList = objectMapper.writeValueAsString(userList);
System.out.println("userlog =>> " + jsonList);

推荐阅读