Jersey JSON serialization

前端 未结 2 1980
天涯浪人
天涯浪人 2021-01-19 13:44

I set up an eclipse WebApp project and placed Jersey and Jackson JARs in the WEB-INF/lib directory. I want to use JSON serialization but didn\'t manage to fix this error:

相关标签:
2条回答
  • 2021-01-19 14:13

    Have you tried adding this to your web.xml?

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

    I believe this tutorial shows what you are trying yo do http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/

    Another one from mkyong http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/

    0 讨论(0)
  • 2021-01-19 14:18

    All you need is to register JacksonJsonProvider. There are many ways to achieve that:

    1. Register the JacksonJsonProvider explicitly in web.xml:
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider</param-value>
    </init-param>
    

    or

    1. Register your class extending javax.ws.rs.core.Application in the web.xml
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.rest.MyApplication</param-value>
    </init-param>
    

    and then do all the configuration in the application class:

    package com.rest;
    
    import org.glassfish.jersey.server.ResourceConfig;
    import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
    
    public class MyApplication extends ResourceConfig {
    
        public MyApplication() {
            packages("com.rest");
            register(JacksonJsonProvider.class);
        }
    

    ResourceConfig is a subclass of javax.ws.rs.Application and gives you some helper methods that makes the registration easy.

    or

    1. Use automatic registration. Just add dependency to jersey-media-json-jackson
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.13</version>
    </dependency>
    

    But be careful. It will register more than you need:

    • JacksonJaxbJsonProvider,
    • JsonParseExceptionMapper,
    • JsonMappingExceptionMapper

    Take a look at the source code to see what it does.

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