Force Spring-Boot to use Gson instead of Jackson
F.e. 1) to add other json artifact, if using maven and google json named gson
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${latestGsonVersion}</version>
</dependency>
2) to set
spring.http.converters.preferred-json-mapper=gson
3) to use it in code, for instance
@Autowired private Gson gson;
There are other ones as well: Jackson Library, Google-Gson Library, JSON-lib, Flexjson, json-io, genson, JSONiJ Library.
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);
}
}