在JAX-RS 2.0中将Jackson配置为JSON提供程序

Tim*_*Tim 14 rest jax-rs jersey jackson glassfish-4

我想将Jackson用作JAX-RS 2.0 Web服务的JSON提供程序.对于JAX-RS,我在GlassFish 4中使用Jersey 2.0.使用JAX-RS 1.x我可以添加

<init-param>
  <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
  <param-value>true</param-value>
</init-param>
Run Code Online (Sandbox Code Playgroud)

在我的web.xml.我怎么能用Jersey 2.0的Jax-RS 2.0做到这一点?我实现了这样的应用程序类

public class MyRESTExampleApplication extends ResourceConfig {
    public MyRESTExampleApplication() {
         packages("com.carano.fleet4all.restExample");
         register(JacksonFeature.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

并将这些行添加到我的web.xml.

<init-param>
    <param-name>javax.ws.rs.Application</param-name>
    <param-value>com.example.restExample.MyRESTExampleApplication</param-value>
</init-param>
Run Code Online (Sandbox Code Playgroud)

但是我通过请求org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException得到一个例外 :找不到媒体类型= application/json,type = class的MessageBodyWriter ...

pom.xml看起来像这样

<dependencies>
  <dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-server</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
  </dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)

Sta*_*Man 21

您应该只需要获取实现jar Jackson JAX-RS提供程序,将其添加到类路径中,它应该可以工作.版本2.x使用基于SPI的自动注册,因此您不需要任何内容web.xml.


Sup*_*054 13

上面的代码对我有用.JAX-RS 2.0具有自动发现功能,因此它应该检测您的jersey-media-json-jackson.jar.我正在使用Tomcat设置,所以我必须register(JacksonFeature.class)像我一样明确地调用我的应用程序.