Dimitri Kopriwa
Dimitri Kopriwa

Reputation: 14375

spring-data-rest and controllers, use the same objectMaper for serializing/deserializing

I have found in the documentation of spring-data-rest that it use it's own objectMapper implementation.

I would like to know if it's possible to reuse this objectMapper so I can have the same entity representation as in spring-data-rest endpoint

For example, without any jackson objectMapper bean I have this

Endpoint: 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" },

But for my controller I have :

"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"
}

This is my own controller implementation :

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

I have no bean for any objectMapper in my code.

How can I get the same serialization ?

Upvotes: 0

Views: 172

Answers (1)

Cepr0
Cepr0

Reputation: 30339

I think you just want to output LocalDate and LocalDateTime fields correctly. If so - add to your project this dependencies:

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

And these annotations to fields:

@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate date;

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

Upvotes: 1

Related Questions