Spring REST:使用 LocalDateTime 对 pojo 的错误请求
Spring REST: Bad Request for pojo with LocalDateTime
Pojo.java
:
public class Pojo {
private LocalDateTime localDateTime;
private String message;
// Getters, setters, toString().
控制器:
@RequestMapping(value = "/test", method = RequestMethod.POST)
public ResponseEntity<?> test(@RequestBody Pojo pojo) {
return ResponseEntity.ok(pojo.toString());
}
集成测试:
Pojo pojo = new Pojo();
pojo.setMessage("message");
pojo.setLocalDateTime(LocalDateTime.now());
String content = jacksonObjectMapper.writeValueAsString(pojo);
this.mockMvc
.perform(post("/test").content(content).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
content
长得像
{"localDateTime":{"dayOfMonth":23,"dayOfWeek":"MONDAY","dayOfYear":144,"monthValue":5,"hour":16,"minute":53,"nano":620000000,"second":6,"month":"MAY","year":2016,"chronology":{"id":"ISO","calendarType":"iso8601"}},"message":"message"}
测试失败,因为返回 400 Bad Request
。如果我在集成测试中评论 pojo.setLocalDateTime ...
,一切正常。
我该怎么做才能让 Spring 在 pojo 中接受 LocalDateTime
?
包括 jackson-datatype-jsr310 数据类型模块,让 Jackson 识别 Java 8 种日期和时间 API 数据类型。
Pojo.java
:
public class Pojo {
private LocalDateTime localDateTime;
private String message;
// Getters, setters, toString().
控制器:
@RequestMapping(value = "/test", method = RequestMethod.POST)
public ResponseEntity<?> test(@RequestBody Pojo pojo) {
return ResponseEntity.ok(pojo.toString());
}
集成测试:
Pojo pojo = new Pojo();
pojo.setMessage("message");
pojo.setLocalDateTime(LocalDateTime.now());
String content = jacksonObjectMapper.writeValueAsString(pojo);
this.mockMvc
.perform(post("/test").content(content).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
content
长得像
{"localDateTime":{"dayOfMonth":23,"dayOfWeek":"MONDAY","dayOfYear":144,"monthValue":5,"hour":16,"minute":53,"nano":620000000,"second":6,"month":"MAY","year":2016,"chronology":{"id":"ISO","calendarType":"iso8601"}},"message":"message"}
测试失败,因为返回 400 Bad Request
。如果我在集成测试中评论 pojo.setLocalDateTime ...
,一切正常。
我该怎么做才能让 Spring 在 pojo 中接受 LocalDateTime
?
包括 jackson-datatype-jsr310 数据类型模块,让 Jackson 识别 Java 8 种日期和时间 API 数据类型。