简体   繁体   English

将实体转换为Json时,为什么LocalDate格式会更改?

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

My objective is to store dates into a database. 我的目标是将日期存储到数据库中。 To do this app I use Springboot, JPA, H2, ... 为此,我使用Springboot,JPA,H2,...

I use LocalDate and the format wished is yyyy-MM-dd . 我使用LocalDate ,希望的格式是yyyy-MM-dd

Entity 实体

@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;
    }

    ...
}

Main 主要

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);
}

Can you help me to understand why dates in entity.toString() are not the same as before with getMethods() ? 您能帮我理解为什么entity.toString()中的日期与getMethods()之前的日期entity.toString()吗?

Thanks for help! 感谢帮助!

LocalDate.parse returns a new LocalDate object. LocalDate.parse返回一个新的LocalDate对象。 The formatting options specified in the DateTimeFormatter get lost aftwerward. DateTimeFormatter指定的格式设置选项会向后丢失。

Jackson (the JSON library you're using) doesn't know how you previously "formatted" the LocalDate , so it uses its own formatting. Jackson (您正在使用的JSON库)不知道您以前如何“格式化” LocalDate ,因此它使用自己的格式。

You can register the JavaTimeModule 您可以注册JavaTimeModule

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

Or you can provide your custom JsonSerializer<T> . 或者,您可以提供自定义的JsonSerializer<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM