【问题标题】:spring-data-rest and controllers, use the same objectMaper for serializing/deserializingspring-data-rest 和控制器,使用相同的 objectMaper 进行序列化/反序列化
【发布时间】:2023-03-14 11:30:01
【问题描述】:

我在 spring-data-rest 的文档中发现它使用自己的 objectMapper 实现。

我想知道是否可以重用这个 objectMapper,这样我就可以拥有与 spring-data-rest 端点相同的实体表示

例如,没有任何杰克逊 objectMapper bean 我有这个

端点:GET /api/companies

"createdDate": { "content": "2016-12-25T12:39:03.437Z" }, "lastModifiedDate": null, "createdById": null, "lastModifiedById": null, "active": true, "name": "A6", "addressSecondary": null, "foundingDate": { "content": "2016-01-01" },

但是对于我的控制器,我有:

"createdDate": {
    "nano": 437000000,
    "epochSecond": 1482669543
},
"lastModifiedDate": null,
"createdById": null,
"lastModifiedById": null,
"active": true,
"name": "A6",
"addressSecondary": null,
"foundingDate": {
    "year": 2016,
    "month": "JANUARY",
    "era": "CE",
    "dayOfYear": 1,
    "dayOfWeek": "FRIDAY",
    "leapYear": true,
    "dayOfMonth": 1,
    "monthValue": 1,
    "chronology": {
    "calendarType": "iso8601",
    "id": "ISO"
}

这是我自己的控制器实现:

@RequestMapping(method = RequestMethod.GET, value = "companies", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<?> testRead() {
    List<Customer> customerRepositoryList = customerRepository.findAll();
    Resources<Customer> resources = new Resources<>(customerRepositoryList);
    return ResponseEntity.ok(resources);
}

我的代码中没有任何 objectMapper 的 bean。

我怎样才能得到相同的序列化?

【问题讨论】:

    标签: spring spring-boot jackson spring-data spring-data-rest


    【解决方案1】:

    我认为您只想正确输出 LocalDateLocalDateTime 字段。 如果是这样 - 将此依赖项添加到您的项目中:

    <!-- JDK 8 DateTime support for Jackson -->
    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
    </dependency>
    

    还有这些字段注释:

    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate date;
    
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime dateTime;
    

    【讨论】:

      猜你喜欢
      • 2017-07-04
      • 2020-09-27
      • 2020-08-10
      • 2017-05-23
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      相关资源
      最近更新 更多