簡體   English   中英

將實體轉換為Json時,為什么LocalDate格式會更改?

[英]Why LocalDate format changed when I transform entity to Json?

我的目標是將日期存儲到數據庫中。 為此,我使用Springboot,JPA,H2,...

我使用LocalDate ,希望的格式是yyyy-MM-dd

實體

@Entity
public class MyObject {

    @Id
    private String id;
    private LocalDate startdate;
    private LocalDate enddate;

    public MyObject() {}

    public MyObject(LocalDate enddate) {
        this.startdate = LocalDate.now();
        this.enddate = enddate;
    }

    ...
}

主要

private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
MyObject myObject = new MyObject(LocalDate.parse("2019-03-01", formatter));
myObject.setId(UUID.randomUUID().toString());
myObjectResource.save(myObject);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
System.out.println(myObject.getStartdate()); // 2019-02-23
System.out.println(myObject.getEnddate()); // 2019-03-01
HttpEntity<String> entity = new HttpEntity<>(this.toJsonString(myObject), headers);
System.out.println(entity.toString()); // <{"id":"ba6649e4-6e65-4f54-8f1a-f8fc7143b05a","startdate":{"year":2019,"month":"FEBRUARY","dayOfMonth":23,"dayOfWeek":"SATURDAY","era":"CE","dayOfYear":54,"leapYear":false,"monthValue":2,"chronology":{"id":"ISO","calendarType":"iso8601"}},"enddate":{"year":2019,"month":"MARCH","dayOfMonth":1,"dayOfWeek":"FRIDAY","era":"CE","dayOfYear":60,"leapYear":false,"monthValue":3,"chronology":{"id":"ISO","calendarType":"iso8601"}}},[Content-Type:"application/json"]>

private String toJsonString(Object o) throws Exception {
    ObjectMapper om = new ObjectMapper();
    return om.writeValueAsString(o);
}

您能幫我理解為什么entity.toString()中的日期與getMethods()之前的日期entity.toString()嗎?

感謝幫助!

LocalDate.parse返回一個新的LocalDate對象。 DateTimeFormatter指定的格式設置選項會向后丟失。

Jackson (您正在使用的JSON庫)不知道您以前如何“格式化” LocalDate ,因此它使用自己的格式。

您可以注冊JavaTimeModule

final ObjectMapper om = new ObjectMapper();
om.registerModule(new JavaTimeModule());

或者,您可以提供自定義的JsonSerializer<T>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM