Error parsing JSON param in java REST

后端 未结 2 1954
暖寄归人
暖寄归人 2020-12-04 03:51

I have recently upgraded my REST API to use jersey 2.x and now I am unable to retrieve JSON body params the way I used to, the methods simply do not get called anymore. My g

相关标签:
2条回答
  • 2020-12-04 04:16

    You may be missing Jersey JSON Jackson (2.x) entity providers support module:

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.19</version>
        <scope>compile</scope>
    </dependency>
    

    It is recommended to use the same Jersey version in all libs.

    0 讨论(0)
  • 2020-12-04 04:35

    You need a JSON provider

    At time of writing, Jersey 2.x integrates with the following modules to provide JSON support:

    • MOXy
    • Java API for JSON Processing (JSON-P)
    • Jackson
    • Jettison

    Using Jackson

    See below the steps required to use Jackson as a JSON provider for Jersey 2.x:

    Adding Jackson module dependencies

    To use Jackson 2.x as your JSON provider you need to add jersey-media-json-jackson module to your pom.xml file:

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.25.1</version>
    </dependency>
    

    To use Jackson 1.x it'll look like:

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson1</artifactId>
        <version>2.25.1</version>
    </dependency>
    

    Registering Jackson module

    Besides adding the dependency mentioned above, you need to register JacksonFeature (or Jackson1Feature for Jackson 1.x) in your Application / ResourceConfig subclass:

    @ApplicationPath("/api")
    public class MyApplication extends Application {
    
        @Override
        public Set<Class<?>> getClasses() {
            Set<Class<?>> classes = new HashSet<Class<?>>();
            classes.add(JacksonFeature.class);
            return classes;
        }
    }
    
    @ApplicationPath("/api")
    public class MyApplication extends ResourceConfig {
    
        public MyApplication() {
            register(JacksonFeature.class);
        }
    }
    

    If you don't have an Application / ResourceConfig subclass, you can register the JacksonFeature in your web.xml deployment descriptor. The specific resource, provider and feature fully-qualified class names can be provided in a comma-separated value of jersey.config.server.provider.classnames initialization parameter.

    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>org.glassfish.jersey.jackson.JacksonFeature</param-value>
    </init-param>
    

    The MessageBodyWriter provided by Jackson is JacksonJsonProvider.


    For more details, check the Jersey documentation about support for common media type representations.

    0 讨论(0)
提交回复
热议问题