如何在Jersey 2.x中添加JSON支持

时间:2014-08-04 10:48:44

标签: java json jersey

我已将我的应用程序从Jersey 1.x迁移到2.x,我试图从web.xml中替换以下条目

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

为了能够将实体作为json。

我在官方文档中读到,我必须通过添加jersey-media-json-jackson依赖来使用Jackson提供商,并注册JacksonFeature。

我添加了以下依赖项:

<dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.4.1</version>
</dependency>

但现在我不知道我必须在我的web.xml文件中添加什么作为

中的值

<param-name>jersey.config.server.provider.packages</param-name>

有什么想法吗?我不想通过像web.xml这样的配置文件来做,而不是在我的代码中。

2 个答案:

答案 0 :(得分:0)

我的配置如下:

    <servlet>
        <servlet-name>REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.<your-company-name-here></param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.beanValidation.enableOutputValidationErrorEntity.server</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

答案 1 :(得分:0)

我使用ResourceConfig课程注册所有内容。我还找到了一个描述如何以其他方式执行的资源(http://blog.dejavu.sk/2013/11/19/registering-resources-and-providers-in-jersey-2/)。

@ApplicationPath("/ws")
public class WsResourceConfig extends ResourceConfig {

    public WsResourceConfig() {
        register(Jackson2Feature.class);
        register(ObjectMapperResolver.class);
        //register(MultiPartFeature.class); // if needed
        //register(new LoggingFilter(LOGGER, true)); // to enable logging

        //register(my resources...); to register my service classes
    }

    private static class ObjectMapperResolver implements ContextResolver<ObjectMapper> {
        private static ObjectMapper mapper = new ObjectMapper();
        static {
            // configure mapper here
        }
        @Override
        public ObjectMapper getContext(Class<?> type) {
            return mapper;
        }
    }

    /**
     * Feature to disable Moxy and Enable Jackson processing
     */
    private static class Jackson2Feature implements Feature {

        @Override
        public boolean configure(FeatureContext context) {
            final String disableMoxy = PropertiesHelper.getPropertyNameForRuntime(
                    CommonProperties.MOXY_JSON_FEATURE_DISABLE,
                    context.getConfiguration().getRuntimeType());
            context.property(disableMoxy, true);

            // add the default Jackson exception mappers and allow jaxb annotations
            context.register(JsonParseExceptionMapper.class);
            context.register(JacksonJaxbJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
            return true;
        }
    }
}