2

ContextResolver泽西岛的 a 是什么,什么是a Provider?两者有什么区别?我在泽西岛使用 Genson。当 Jersey 在类路径中找到 Genson JAR 时,Genson 会自动注册。Genson JAR 的 WEB-INF/services 目录包含一个名为“org.glassfish.jersey.internal.spi.AutoDiscoverable”的文件。

按照该AutoDiscoverable路径,默认情况下 Genson/Jersey 会自动注册以下类:

@Provider
@Consumes({MediaType.APPLICATION_JSON, "text/json", "application/*+json"})
@Produces({MediaType.APPLICATION_JSON, "text/json", "application/*+json"})
public class GensonJsonConverter implements MessageBodyReader<Object>, MessageBodyWriter<Object> {

     private final ContextResolver<GensonJaxRSFeature> _gensonResolver;

这里是更多混乱发挥作用的地方:查看它建议创建自定义提供程序的 Genson 文档,如下所示:

    @Provider
    public class GensonProvider implements ContextResolver<Genson> {
    private final Genson genson = new GensonBuilder().setSkipNull(true).create();
    }

然而,该提供者实现了一个不像内部 Genson 那样ContextResolver的/Writer 。MessageBodyReader有什么不同?此外,该提供商不会与默认自动注册的一样的事情!特别是,它会忽略JAXB 标签,例如@XmlTransient! 深入研究 Genson 源代码GensonJaxRSFeature,我看到 Genson 对象是这样创建的:

private static final Genson _defaultGenson = new GensonBuilder()
      .withBundle(new JAXBBundle())
      .useConstructorWithArguments(true)
      .create();

从中和 Genson 文档中,我可以看到“JAXBBundle”可能是导致 Genson 关注 JAXB 注释的原因。

主要问题:

我想使用在 Jersey 自动注册的默认 Genson JSON 提供程序,但我想在其上设置一些自定义属性。正如我所说,当我注册我的自定义提供程序时,它不使用默认的 Genson !


更新:

这就是我现在正在做的事情,并且有效。但是,@eugen 下面的解决方案是 Genson 推荐的解决方案。

@Provider
public class GensonProvider implements ContextResolver<GensonJaxRSFeature> {
    private final GensonJaxRSFeature _gensonResolver = new GensonJaxRSFeature();

    private static final Genson _defaultGenson = new GensonBuilder()
              .withBundle(new JAXBBundle())
              .useConstructorWithArguments(true)
              .setSkipNull(true)
              .create();

   @Override
   public GensonJaxRSFeature getContext(Class<?> type) {
        return _gensonResolver.use(_defaultGenson);
   }
}
4

1 回答 1

2

就像我们的世界一样,对于同一个问题,有多种解决方案。Jersey 似乎鼓励使用 ResourceConfig 而不是定义自定义提供程序。所以这就是你如何使用资源配置来实现它(来自 jersey docs here和 Genson documentation here)。

public class MyApplication extends ResourceConfig {
    public MyApplication() {
      Genson genson = new GensonBuilder()
              .withBundle(new JAXBBundle())
              .useConstructorWithArguments(true)
              .setSkipNull(true)
              .create();

      register(new GensonJaxRSFeature().use(genson));
    }
}

但是,当然,您与提供商合作的方式也很好。

于 2016-06-30T00:18:09.697 回答