解决Spring Boot中使用@RequestBody无法解析LocalDateTime的问题

938 阅读1分钟

1、添加配置类

@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper()
                .registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());
    }
}

2、实体类添加@JsonFormat注解

@Data
public class UserDTO {
	//@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime dateTime;
}

3、controller层使用@RequestBody注解进行测试

@RestController
@RequestMapping
public class UserController {

    @PostMapping("test")
    public UserDTO user1(@RequestBody UserDTO userDTO) {
        //...
    }
}

3、测试返回结果:{"dateTime":"2019-01-12 12:09:12"}