在我的Spring REST Web应用程序中,我试图使控制器与Java8 LocalTime一起使用。我正在POST请求中发送此Json
{ "hour": "0", "minute": "0", "second": "0", "nano": "0" }
我得到HttpMessageNotReadableException以下杰克逊错误
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
据我了解,Google应该自动为Java8.time对象注册JSR-310模块。
我没有使用@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()); } }
您能建议我的配置出了什么问题吗?
您的配置没有错。
我建议您将Spring Boot更新为1.2.0.RELEASE。它使用Spring 4.1.3软件包,已解决的问题MappingJackson2HttpMessageConverter。要获取更多信息,请阅读:https : //github.com/spring-projects/spring- boot/issues/1620#issuecomment-58016018。就我而言,它奏效了。
MappingJackson2HttpMessageConverter
如果您不想更新Spring Boot版本,则可能要做的至少是LocalTime像这样显式地注释的字段:
LocalTime
@JsonSerialize(using = DateTimeSerializer.class) @JsonDeserialize(using = DateTimeDeserializer.class) private LocalTime date;