Spring web:@RequestBody Json转换为Java8 LocalTime无法正常工作

时间:2014-12-10 16:19:18

标签: json spring-mvc java-8 spring-boot java-time

在我的Spring REST webapp中,我正在尝试让控制器使用Java8 LocalTime。 我在POST请求中发送这个Json

{
    "hour": "0",
    "minute": "0",
    "second": "0",
    "nano": "0"
}

我得到HttpMessageNotReadableException以下杰克逊错误

Could not read JSON: No suitable constructor found for type [simple type, class java.time.LocalTime]: can not instantiate from JSON object (need to add/enable type information?) 
at [Source: org.apache.catalina.connector.CoyoteInputStream@58cfa2a0; line: 2, column: 5]; 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class java.time.LocalTime]: can not instantiate from JSON object (need to add/enable type information?) 
at [Source: org.apache.catalina.connector.CoyoteInputStream@58cfa2a0; line: 2, column: 5]

我正在使用spring-web-4.0.3.RELEASE和spring-boot-starter-web-1.0.2.RELEASE,jackson-databind-2.4.2和jackson-datatype-jsr310-2.4.2

根据我的浏览方式,Spring应该自动为Java8.time对象注册JSR-310模块。

我找到了问题的答案,但它对我不起作用:Spring Boot and Jackson, JSR310 in response body

我没有使用@EnableWebMvc注释的配置,这是我唯一的配置类

@EnableAutoConfiguration
@ComponentScan
@EnableAspectJAutoProxy()
@Configuration
@ImportResource(value = "Beans.xml") 
public class Application extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToLocalDateTime());
        registry.addConverter(new LocalDateTimeToString());
        registry.addConverter(new StringToLocalDate());
        registry.addConverter(new LocalDateToString());
        registry.addConverter(new StringToLocalTime());
        registry.addConverter(new LocalTimeToString());
    }
}

你能说出我的配置有什么问题吗?

3 个答案:

答案 0 :(得分:4)

您需要将模块注册为Spring的Bean才能查看并设置它

@Configuration
public class JacksonConfiguration {

    @Bean
    public JSR310Module jsr310Module() {
        return new JSR310Module();
    }
}

答案 1 :(得分:4)

您的配置没有任何问题。

我建议你将Spring Boot更新到1.2.0.RELEASE。它使用Spring 4.1.3软件包,解决了MappingJackson2HttpMessageConverter的问题。要获得更多信息,请阅读:https://github.com/spring-projects/spring-boot/issues/1620#issuecomment-58016018。它适用于我的情况。

如果您不想更新Spring Boot版本,可能至少可以明确地注释LocalTime的字段:

@JsonSerialize(using = DateTimeSerializer.class)
@JsonDeserialize(using = DateTimeDeserializer.class)
private LocalTime date;

答案 2 :(得分:1)

使用SpringBoot 1.5,我使用了以下依赖项,开箱即用!

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>