简体   繁体   中英

Spring REST: Bad Request for pojo with LocalDateTime

Pojo.java :

public class Pojo {
    private LocalDateTime localDateTime;
    private String message;
    // Getters, setters, toString().

Controller:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public ResponseEntity<?> test(@RequestBody Pojo pojo) {
    return ResponseEntity.ok(pojo.toString());
}

Integration test:

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 looks like

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

The test fails because 400 Bad Request is returned. If I comment pojo.setLocalDateTime ... in the integration test, everything works fine.

What can I do so that Spring accepts LocalDateTime in the pojo?

包括jackson-datatype-jsr310数据类型模块,以使Jackson能够识别Java 8 Date&Time API数据类型。

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