Configure Jackson as JSON Provider in JAX-RS 2.0

北战南征 提交于 2019-11-29 11:56:16

问题


I want to use Jackson as JSON provider for my JAX-RS 2.0 webservice. For JAX-RS I use Jersey 2.0 in GlassFish 4. With JAX-RS 1.x I can add

<init-param>
  <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
  <param-value>true</param-value>
</init-param>

in my web.xml. How can i do this in Jax-RS 2.0 with Jersey 2.0? I implement a application class like this

public class MyRESTExampleApplication extends ResourceConfig {
    public MyRESTExampleApplication() {
         packages("com.carano.fleet4all.restExample");
         register(JacksonFeature.class);
    }
}

and add these lines to my web.xml.

<init-param>
    <param-name>javax.ws.rs.Application</param-name>
    <param-value>com.example.restExample.MyRESTExampleApplication</param-value>
</init-param>

But I get an exception by the request org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class ...

My pom.xml looks like this

<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>

回答1:


You should only need to get the implementation jar Jackson JAX-RS provider, add that to your classpath, and it should work. Version 2.x uses SPI-based auto-registration, so that you do not need anything in web.xml.




回答2:


The above code worked for me. JAX-RS 2.0 has auto discovery feature so it should detect your jersey-media-json-jackson.jar. I am using a Tomcat setup so, I had to explicitly call register(JacksonFeature.class) in my application as you do.



来源:https://stackoverflow.com/questions/18741954/configure-jackson-as-json-provider-in-jax-rs-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!