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.
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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With