2016-05-23 67 views
0

Pojo.java弹簧安置:坏请求对POJO与LocalDateTime

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

回答

1

包含jackson-datatype-jsr310数据类型模块以使Jackson识别Java 8日期&时间API数据类型。

+0

This works。现在'content'看起来像'{“localDateTime”:[2016,5,23,17,26,15,226000000],“message”:“message”}'并且Spring接受它。 –