Home > Net >  MappingJacksonHttpMessageConverter cannot be resolved to a type
MappingJacksonHttpMessageConverter cannot be resolved to a type

Time:07-09

I am trying to upgrade Spring Application (not using Spring Boot) from 2.3.2.RELEASE to 5.3.20 (latest version as of today), I do see below code is breaking and

Code:

@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();

        ObjectMapper defaultMapper = new ObjectMapper();
        defaultMapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, true);
        defaultMapper.configure(SerializationConfig.Feature.REQUIRE_SETTERS_FOR_GETTERS, true);
        mappingJacksonHttpMessageConverter.setObjectMapper(defaultMapper);

        converters.add(mappingJacksonHttpMessageConverter);
    }

What's the replacement of import org.codehaus.jackson.map.ObjectMapper to jacksondata bind for below code?

ObjectMapper defaultMapper = new ObjectMapper();
        defaultMapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, true);
        defaultMapper.configure(SerializationConfig.Feature.REQUIRE_SETTERS_FOR_GETTERS, true);
        mappingJacksonHttpMessageConverter.setObjectMapper(defaultMapper);

CodePudding user response:

I was able to do like below

com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
objectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
mappingJacksonHttpMessageConverter.setObjectMapper(objectMapper);

CodePudding user response:

The MappingJacksonHttpMessageConverter is for Jackson1, which isn't supported anymore with Spring 5, it was deprecated in Spring 4.

You will need to migrate to Jackson2 and use the MappingJackson2HttpMessageConverter instead.

Instead of constructing the ObjectMapper manually I strongly suggest using the Jackson2ObjectMapperBuilder to construct the ObjectMapper. It will automatically detect and register well known Modules and allows for easier configuration.

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

    ObjectMapper mapper = Jackson2ObjectMapperBuilder.json()
      .defaultViewInclusion(true)
      .featuresToEnable(SerializationConfig.Feature.REQUIRE_SETTERS_FOR_GETTERS)
      .build(); 

    MappingJackson2HttpMessageConverter converter = 
        new MappingJackson2HttpMessageConverter(mapper);
    converters.add(converter);
}

Finally use the constructor instead of the setter as that saves building an additional ObjectMapper (done in the default constructor of the MappingJackson2HttpMessageConverter and then throwing it away) saves a few CPU cycles.

  • Related