我定义了@Bean
objectMapper
并设置了日期格式,如下所示:
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
当方法返回正常ResponseEntity<SomeDTO>
时,它有效。示例 JSON 响应:
{
"id": 888,
"createdDate": "2017-11-06 13:50",
}
但是当我的控制器方法返回:ResponseEntity<PagedResources<SomeDTOResponse>>
时,createdDate
没有反序列化,我得到:
{
"_embedded": {
"someEntityResponseList": [
{
"id": 877,
"createdDate": 1509877100151
}
]
},
"_links": {
...
},
"page": {
...
}
}
我的控制器:
@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);
}
当我把断点放在最后一行return...
时,对象response
包含:createdDate = {Timestamp@12184} "2017-11-05 10:54:14.345"
。 mapToResponse()
这是我的自定义方法,但这不是问题。那么我怎样才能得到正确的结果,正确的反序列化呢?
我的其他课程:SomeDtoResponse
和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;
}
确保您使用的 Date 类应为以下类型:
import java.util.Date;
如果它是Java.sql.Date,那么它会导致你面临的问题。我希望这将解决您的问题。