I am trying to force SpringBoot to use Gson instead of Jackson. I've read most of the articles I've found online and I am still seeing Jackson being used. Here's what I've done
- Added
spring:
http: { converters: { preferred-json-mapper: gson } }
mvc: { converters: {preferred-json-mapper: gson } }
in application.yaml
- Updated POM
- Added
gsondependency - Added
jackson-databindto exclusion list inspring-boot-starter-webdepedency.
- Added
- Added
@EnableAutoConfiguration(exclude = JacksonAutoConfiguration.class)to main class. - Written below
@Configurationclass:
@Configuration
@Slf4j
public class MyConfig implements WebMvcConfigurer {
@Override
public void extendMessageConverters (List<HttpMessageConverters<?>> converters) {
log.debug("Setting gson converter");
converters.add(new GsonHttpMessageConverter(myCustomGsonInstance()));
}
public Gson myCustomGsonInstance() {
return new Gson();
}
}
When running tests in debug, I can see that Jackson is still listed in the HttpMessageConverters list and Gson is not.
Update: This behavior is seen while running live and in the below test class.
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = MOCK)
@ExtendWith(MockitoExtension.class)
public class MyTestClass {
@Autowired
private MyController controller;
private MockMvc mockMvc;
@BeforeEach
public void setUp(){
mockMvc = MockMvcBuilders.standaloneSetup(controller)
// .setMessageConverters(new GsonHttpMessageConverter(myCustomGsonInstance())) // if I add this, the test passes.
.build();
}
@Test
public void happyFlow(){
// given
URI uri = "/test/uri";
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
// when
String responseBody = mockMvc.perform(get(uri).headers(headers)).andReturn().getResponse().getContentAsString();
// then
assertThat(responseBody, wasSerializedByGson());
}
}