2016-11-24 46 views
3

弹簧引导1.4.2参考权利要求书:力弹簧-Boot的使用GSON代替杰克逊

spring.http.converters.preferred-JSON映射器=杰克逊#优选JSON映射器用于HTTP消息转换。设置为“gson”强制使用Gson

我们做到了。

  • 我们为preferred-json-mapper设置了gson。
  • 我们添加了Gson作为我们项目的依赖项。

但仍使用杰克逊。

最后,我们设法强制Spring-Boot在使用Gson之后,排除了Maven中已经指出给Jackson的所有传递依赖关系。

现在的问题是。是否只有这样才能迫使Spring-Boot使用Gson而不是Jackson?我们是否真的需要排除指向杰克逊的所有传递性依赖?首选-json-mapper设置是不够的?

+0

为了避免任何浪费时间试图回答这个问题,这里还有为它春天启动的问题:https://github.com/spring-projects/spring-boot/问题/ 7518 –

回答

0

它发生在Spring Boot使用的旧的* .xml配置的一部分中,我们有<mvc:annotation-driven/>

它导致创建的RequestMappingHandlerAdapter第二次与默认转换器没有GsonHttpMessageConverter。

0

恩,WebMvcConfigurerAdapter已弃用。作为春天的5.0做到这一点:

@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); 
    } 
}