Spring Boot中使用@RequestBody对json解

2018-04-12  本文已影响3778人  黑色小核

场景描述

.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

上一篇 下一篇

猜你喜欢

热点阅读