@JsonFormat處理LocalDateTime失效的問題
@JsonFormat處理LocalDateTime失效
Failed to convert property value of type ‘java.lang.String’ to required type ‘localdatetime’ for property ‘time’ xxxx
Api 請求參數(shù)中,通過需要用時間LocalDateTime,希望通過@JsonFormat() 處理時間格式:
@GetMapping("/user")
public UserDTO getUser(UserDTO name) {
?? ?xxx
}
@Data
public class UserDTO {
? ? @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
? ? LocalDateTime time;
}當我們通過get請求,通過表單的方式提交時,就會報上面按個轉換異常參數(shù);
解決:
方案一:改成請求體的方式提交,@RequestBody
? ? //get請求
? ? @GetMapping("/user")
? ? public UserDTO getUser(@RequestBody UserDTO name) {
? ? }
? ? // post 請求
? ? @PostMapping("/user")
? ? public UserDTO getUser(@RequestBody UserDTO name) {
? ? }方案二:同時添加@DateTimeFormat()注解這個是Spring提供的注解
@Data
public class UserDTO {
? ? @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
? ? @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
? ? LocalDateTime time;
}@DateTimeFormat用于將請求參數(shù)序列化@JsonFormat()將返回參數(shù)序列話
@JsonFormat格式化LocalDateTime失敗
我們可以使用SpringBoot依賴中的@JsonFormat注解,將前端通過json傳上來的時間,通過@RequestBody自動綁定到Bean里的LocalDateTime成員上。具體的綁定注解使用方法如下所示。
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
出現(xiàn)問題的版本
我使用Spring Boot 2.0.0 時,直接在字段上加上@JsonFormat 注解就可以完成數(shù)據(jù)的綁定。
而在使用Spring Boot 1.5.8時,只在字段上加上@JsonFormat 注解,在數(shù)據(jù)綁定時無法將Date類型的數(shù)據(jù)自動轉化為字符串類型的數(shù)據(jù)。
解決:
1.將SpringBoot版本升級為2.0.0及以上。
2.如果不升級SpringBoot版本,可以按照下面的方式解決問題。
不升級SpringBoot版本,添加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;
? ? }
}或者在application.properties添加如下配置:
spring.jackson.serialization.write-dates-as-timestamps=false
或者只注冊JavaTimeModule,添加下面的Bean
@Bean
public ObjectMapper serializingObjectMapper() {
? ObjectMapper objectMapper = new ObjectMapper();
? objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
? objectMapper.registerModule(new JavaTimeModule());
? return objectMapper;
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java Swing JToggleButton開關按鈕的實現(xiàn)
Java中關于MouseWheelListener的鼠標滾輪事件詳解

