場景描述
-
需求
需求主要是將前端通過json傳上來的時間,通過
@RequestBody
自動綁定到Bean里的LocalDateTime
成員上。 -
綁定方法
使用
@JsonFormat
注解,示例:@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
-
出現(xiàn)問題的版本
我使用Spring Boot 2.0.0 時,直接在字段上加上
@JsonFormat
注解就可以完成數(shù)據(jù)的綁定。而在使用Spring Boot 1.5.8時,只在字段上加上
@JsonFormat
注解,在數(shù)據(jù)綁定時就會報錯。 報錯信息
.w.s.m.s.DefaultHandlerExceptionResolver :
Failed to read HTTP message:
org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error:
Can not construct instance of java.time.LocalDateTime:
no String-argument constructor/factory method to deserialize from String value ('2018-04-12 14:00:16');
nested exception is com.fasterxml.jackson.databind.JsonMappingException:
Can not construct instance of java.time.LocalDateTime:
no String-argument constructor/factory method to deserialize from String value ('2018-04-12 14:00:16')
at [Source: java.io.PushbackInputStream@5cf71c5b; line: 9, column: 17]
(through reference chain:
com.semonx.gateway.comm.entity.ErrCodePushVo["errcodepushList"]
->java.util.ArrayList[0]
->com.semonx.gateway.comm.entity.ErrCodePushSon["happentime"])
解決方法
添加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;
}
}
參考資料
新的Jackson模塊:https://github.com/FasterXML/jackson-modules-java8
其他人遇到的類似的情況:http://www.jb51.net/article/136389.htm