简体   繁体   中英

Deserialize date with PagedResources/embedded object. Jackson. Spring

I defined @Bean objectMapper and set the date format like this:

ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));

And it works when method return the normal ResponseEntity<SomeDTO> . Sample JSON response:

{
    "id": 888,
    "createdDate": "2017-11-06 13:50",
}

But when my controller method returns: ResponseEntity<PagedResources<SomeDTOResponse>> , then createdDate isn't deserialized and I get:

{
    "_embedded": {
        "someEntityResponseList": [
            {
                "id": 877,
                "createdDate": 1509877100151
            }
        ]
    },
    "_links": {
        ...
    },
    "page": {
        ...
    }
}

My controller:

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<PagedResources<SomeDTOResponse>> getAllActiveAuctionsForLoggedUser(
        Pageable pageable, PagedResourcesAssembler assembler) {
    Page<SomeEntity> someEntites = someEntityService.getAllSomeEntities(pageable);

Page<SomeDTOResponse> response = assembler.toResource(someEntites.map(entity -> mapToResponse(entity))
return new ResponseEntity<>(response, HttpStatus.OK);
}

When I put breakpoint in last line return... , the object response contains: createdDate = {Timestamp@12184} "2017-11-05 10:54:14.345" . mapToResponse() it's my custom method, but it's not the problem. So how can I get the correct result, correct deserialization?

My other classes: SomeDtoResponse and SomeEntity .

@Data
public class SomeDtoResponse {

    private Long id;
    private Date createdDate;
}

@Entity
@Table(name = "SOME_ENTITY")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class SomeEntity {

    @Id
    @GeneratedValue
    @Column(name = "SOME_ENTITY_ID")
    private Long id;

    @NotNull
    private Date createdDate;
}

Make sure that the Date class you are using should be of following type:

import java.util.Date;

If it's of Java.sql.Date, then it cause the problems like you are facing. I hope this will resolve your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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