Jersey中自定义Jackson的版本

最近在升级Jboss的时候,升级了我们使用jersey的版本,但是遇到了一个问题,jersey server端和client端使用的Jackson版本不一致的问题,于是就研究了一下怎么使用我们指定版本的Jackson。
在server端,我们可以使用实现ContextResolver来指定使用的Jackson版本,并且可以自定义ObjectMapper, 在getContext中可以使用我们想使用的Jackson版本,并且添加一下我们需要的相应地配置。注意其中的注解是 @Provider只有加了这个注解jersey才回去调用我们定义的getContext 方法, 当然也可以在ResourceConfig中register FWObjectMapperProvider也能实现一样的效果。

@Providerpublic class FWObjectMapperProvider implements ContextResolver {    String className = FWObjectMapperProvider.class.getName();     public ObjectMapper getContext(Class type) {        }    public FWObjectMapperConfig getMappingConfig() throws Exception {          }    
     private AnnotationIntrospector getAnnotationIntrospector(String clazzName) throws Exception {        return (AnnotationIntrospector)Class.forName(clazzName).newInstance();    }}

server端还有一个需要注意的点是,如果我们想在jersey 2.x版本中使用jackson1.X版本,我们需要在ResourceConfig中添加下面这段代码:

public class FWServiceResourceConfigProvider extends ResourceConfig {    public FWServiceResourceConfigProvider() {        this.register(Jackson1Feature.class);    }}

注意其中是Jackson1Feature.class,不要误写成JacksonFeature.class。client端则没有这个要求。
在client端通过在ClientConfig中注册JacksonJsonProvider来指定相应的版本,:

ClientConfig clientConfig = new ClientConfig();clientConfig.property("jersey.config.client.disableAutoDiscovery", true);clientConfig.register(JacksonFeature.class);clientConfig.register(JacksonJsonProvider.class);
Client client = ClientBuilder.newClient(config)

然后使用上面的client调用server端服务即可保持前后台是一致的,对于我们这种jersey升级到了2.x版本但是项目中还是使用jackson 1.9.11版本的情况下,就可以通过上面这种方式替换jersey使用的默认jackson版本,从而兼容我们现在的代码。并且保持前后端版本的一致不会出现转换报错的情况。

你可能感兴趣的:(Jersey中自定义Jackson的版本)