我试图强迫SpringBoot使用Gson而不是杰克逊。我已经阅读了我在网上找到的大部分文章,我仍然看到杰克逊被使用。以下是我所做的
spring:
http: { converters: { preferred-json-mapper: gson } }
mvc: { converters: {preferred-json-mapper: gson } }在application.yaml中
gson依赖项jackson-databind添加到排除列表中,使spring-boot-starter-web不再学究。@EnableAutoConfiguration(exclude = JacksonAutoConfiguration.class)添加到主类中。@Configuration类下面:@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();
}
}在调试中运行测试时,我可以看到杰克逊仍然列在HttpMessageConverters列表中,而Gson没有。
更新:在运行时和下面的测试类中都可以看到这种行为。
@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());
}
}发布于 2020-09-24 16:34:36
看起来您在配置首选的JSON映射程序时使用了错误的属性。您正在使用spring.http.converters.preferred-json-mapper,但正确的属性是spring.mvc.converters.preferred-json-mapper。在application.yaml中,这将是以下内容:
spring:
mvc:
converters:
preferred-json-mapper: gson发布于 2020-09-24 20:36:06
Spring附带Gson自动配置支持:源代码
因此,除了启用yaml属性之外,您还必须使用Gson单例实例以供WebMvcConfigurer使用:
@Configuration
@Slf4j
public class MyConfig implements WebMvcConfigurer {
@Autowired
private Gson gson;
@Override
public void extendMessageConverters (List<HttpMessageConverters<?>> converters) {
log.debug("Setting gson converter");
converters.add(new GsonHttpMessageConverter(gson));
}
}和从安迪·威尔金森借来的yaml属性
spring:
mvc:
converters:
preferred-json-mapper: gson使用此设置,Spring使用的Gson实例与配置中的相同。
在你的测试中,应该是这样的:
@WebMvcTest(MyController.class)
public class MyTestClass {
@Autowired
private MockMvc mockMvc;
@Autowired
private MyController controller;
@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());
}
}https://stackoverflow.com/questions/64050458
复制相似问题