代码之家  ›  专栏  ›  技术社区  ›  Royce

当我将实体转换为JSON时,为什么本地日期格式发生了变化?

  •  0
  • Royce  · 技术社区  · 5 年前

    我的目标是将日期存储到数据库中。为了做这个应用,我使用了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() ?

    谢谢你的帮助!

    1 回复  |  直到 5 年前
        1
  •  1
  •   LppEdd    5 年前

    LocalDate.parse 返回新的 LocalDate 对象。中指定的格式选项 DateTimeFormatter 两天前迷路。

    Jackson (the JSON 你正在使用的库)不知道你以前是如何“格式化”的 本地日期 ,因此它使用自己的格式。

    您可以注册 JavaTimeModule

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

    或者你可以提供你的定制 JsonSerializer<T> .