需求
需求主要是将前端通过json传上来的时间,通过@RequestBody自动绑定到Bean里的LocalDateTime成员上。
绑定方法
使用@JsonFormat 注解,示例:@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
解决方法
添加Jackson对Java Time的支持后,就能解决这个问题。
在pom.xml中添加:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
添加JavaConfig,自动扫描新添加的模块:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper serializingObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
return objectMapper;
}
}
示例
controller
@GetMapping()
public List<HiCourseSchedule> findAll(@ApiParam(name = "startDate", value = "上课时间", required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
@ApiParam(name = "endDate", value = "下课时间", required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
entity
@ApiModelProperty(value = "上课时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime classHourStart;
@ApiModelProperty(value = "下课时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime classHourDown;
网友评论