Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring web: @RequestBody Json conversion for Java8 LocalTime not working

In my Spring REST webapp, I'm trying to get a controller working with Java8 LocalTime. I'm sending this Json in a POST request

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

and I get a HttpMessageNotReadableException with the following Jackson error

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]

I'm using spring-web-4.0.3.RELEASE with spring-boot-starter-web-1.0.2.RELEASE, jackson-databind-2.4.2 and jackson-datatype-jsr310-2.4.2

From what I understood googling around, Spring should automatically register JSR-310 modules for Java8.time objects.

I found an answer to my problem, but it does not work for me: Spring Boot and Jackson, JSR310 in response body

I have no configurations annotated with @EnableWebMvc and here is my only configuration class

@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());
    }
}

Can you suggest what's wrong in my configuration?

like image 524
Ste Avatar asked Jan 10 '23 07:01

Ste


1 Answers

There is nothing wrong with your configuration.

I suggest you to update Spring Boot to 1.2.0.RELEASE. It uses Spring 4.1.3 packages, which have resolved issue with MappingJackson2HttpMessageConverter. To get more info read: https://github.com/spring-projects/spring-boot/issues/1620#issuecomment-58016018 . It worked in my case.

If you do not want to update Spring Boot version, probably the least you can do is to annotate LocalTime's fields explicitly like that:

@JsonSerialize(using = DateTimeSerializer.class)
@JsonDeserialize(using = DateTimeDeserializer.class)
private LocalTime date;
like image 167
AdamBat Avatar answered Jan 12 '23 07:01

AdamBat