Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Spring-Boot to use Gson instead of Jackson

Tags:

spring-boot

Spring-Boot 1.4.2 reference claims:

spring.http.converters.preferred-json-mapper=jackson # Preferred JSON mapper to use for HTTP message conversion. Set to "gson" to force the use of Gson

We did it.

  • We set gson for preferred-json-mapper.
  • We have added Gson as dependency of our project.

But still Jackson was used.

Finally we manage to force Spring-Boot to use Gson after exclude all transitive dependencies in Maven which have been pointing out to Jackson.

Now the question is. Is it the only way to force Spring-Boot to use Gson instead of Jackson? Do we really need to exclude all transitive dependencies pointing out to Jackson? The preferred-json-mapper setting is not enough?

like image 372
Ziemowit Stolarczyk Avatar asked Nov 24 '16 12:11

Ziemowit Stolarczyk


1 Answers

Well, WebMvcConfigurerAdapter is deprecated. As of Spring 5.0 do this:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public Gson gson() {
        GsonBuilder b = new GsonBuilder();
        b.registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY);
        b.registerTypeAdapterFactory(DateTypeAdapter.FACTORY);
        b.registerTypeAdapterFactory(TimestampTypeAdapter.FACTORY);
        b.registerTypeAdapterFactory(LocalDateTypeAdapter.FACTORY);
        b.registerTypeAdapterFactory(LocalDateTimeTypeAdapter.FACTORY);
        return b.create();
    }

    @Override
    public void configureMessageConverters(
        List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        stringConverter.setWriteAcceptCharset(false);
        stringConverter.setSupportedMediaTypes(Collections
            .singletonList(MediaType.TEXT_PLAIN));
        converters.add(stringConverter);
        converters.add(new ByteArrayHttpMessageConverter());
        converters.add(new SourceHttpMessageConverter<>());
        GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
        gsonHttpMessageConverter.setGson(gson());
        gsonHttpMessageConverter.setSupportedMediaTypes(Arrays
            .asList(MediaType.APPLICATION_JSON));
        converters.add(gsonHttpMessageConverter);
    }
}
like image 138
lordUhuru Avatar answered Sep 19 '22 14:09

lordUhuru