简体   繁体   中英

How do I programmatically configure Jersey to use Jackson for JSON (de)serialization?

I'm using Jersey together with Grizzly to create a JSON web service. I initialize it as follows:

    final ResourceConfig rc = new PackagesResourceConfig("amplify.api.resources");
    rc.getProperties().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
    return GrizzlyServerFactory.createHttpServer(BASE_URI, rc);

I have no web.xml file. I noticed that Jersey was mapping single element lists to be "element" rather than "[element]" as I would expect. It seems that apparently this is because Jersey uses a POJO->JSON mapper other than Jackson, and for reasons that elude me, they thought it would be a great idea to automatically unwrap single-element lists.

I found explanations of how to make Jersey use Jackson by configuring the web.xml file, but since I don't have a web.xml, I'm unsure how to do this.

Can anyone explain how I can programmatically configure Jersey to use Jackson?

I have response from how do I enable POJO-mapping programatically in Jersey using Grizzly2?

The idea is to add jersey-json library to your application.

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>${jersey.version}</version>
</dependency>

Take a look at the JacksonJsonProvider in the Jackson jax-rs module .

You need to hook it (or a subclass such as JacksonJaxbJsonProvider ) in the Jersey-recognized IoC container (its own by default, but I personally prefer Guice), or otherwise get it registered as an @Provider

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM