Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Jackson deserializer does not get registered in Spring

I'm trying to deserialize some JSON with Jackson in Spring. I have configured it to use a custom MappingJackson2HttpMessageConverter and I can see it gets registered. Still, when trying to deserialize, I see that it is not using my custom MappingJackson2HttpMessageConverter but that instead it uses the defaultList of HttpMessageConverters (in other words it's not overridden). Any idea how it could be solved ? Thanks.

package com.bigid.scanner.service.restapi;

import com.bigid.scanner.api.datalink.DataLink;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.text.SimpleDateFormat;
import java.util.List;

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.mixIn(DataLink.class, PolymorphicDataLinkMixin.class);
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }
}
like image 222
jhagege Avatar asked Sep 01 '25 21:09

jhagege


1 Answers

Many of these answers look good. In addition, if you are using Spring Boot, be sure you don't have the @EnableWebMvc annotation on your configuration. I spent many hours trying numerous different ways (some of which are documented in the questions and responses here) to register/configure custom Jackson Serializers and Deserializers, none of which were working correctly. While debugging I could see the registration code was being invoked on application startup, yet the De/Serializers were never called. Apparently the @EnableWebMvc was overriding these registrations in the Spring Boot environment. Simply removing this annotation made everything work just as expected.

like image 184
rscarter Avatar answered Sep 04 '25 03:09

rscarter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!