我想将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>
在我的web.xml
中。我怎么能用Jersey 2.0的Jax-RS 2.0做到这一点?
我实现了像这样的应用程序类
public class MyRESTExampleApplication extends ResourceConfig {
public MyRESTExampleApplication() {
packages("com.carano.fleet4all.restExample");
register(JacksonFeature.class);
}
}
并将这些行添加到我的web.xml
。
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.example.restExample.MyRESTExampleApplication</param-value>
</init-param>
但是我的请求得到了例外 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>
答案 0 :(得分:21)
您应该只需要获取实现jar Jackson JAX-RS provider,将其添加到类路径中,它应该可以工作。版本2.x使用基于SPI的自动注册,因此您不需要web.xml
中的任何内容。
答案 1 :(得分:13)
以上代码对我有用。 JAX-RS 2.0具有自动发现功能,因此它应该检测到您的jersey-media-json-jackson.jar
。我正在使用Tomcat设置,所以我必须像我一样在我的应用程序中明确地调用register(JacksonFeature.class)
。