Jersey 2.6 Jackson 提供者注册提供者、Jersey、Jackson

2023-09-07 08:51:03 作者:歪腻I

我正在使用 Jersey 2.6 实现 REST Web 服务,

I'm implementing REST web service with Jersey 2.6,

我在注册 Jackson Provider 以支持 JSON 时遇到麻烦,我已根据 jeresy 文档(https://jersey.java.net/documentation/2.6/user-guide.html#json.jackson).

I'm having troubles of registering a Jackson Provider for JSON support, I have implemented according to the jeresy documentation (https://jersey.java.net/documentation/2.6/user-guide.html#json.jackson).

添加 maven 依赖 - jersey-media-json-jackson实现了一个 ContextResolver 类.使用@Provider 对其进行注释以启用自动发现功能"web.xml 中有提供者类的包名,以便在扫描过程中注册提供者.

参考:http://blog.dejavu.sk/2013/11/19/registering-resources-and-providers-in-jersey-2/

由于某种原因,Jackson JSON 提供程序未注册,我是否遗漏了什么?

For some reason Jackson JSON provider is not registered, am I missing something?

推荐答案

在 Jersey 2.9 之前,该功能不会自动发现.我们需要 (1) 在 Application/ResourceConfig 子类中显式注册 JacksonFeature,(2) 在要扫描的包的 web.xml 中列出 Jackson 包,或者(3) 将 JacksonFeature 添加到 web.xml 中的提供者列表中

Up until Jersey 2.9, that feature is not auto-discovered. We need to either (1) explicitly register the JacksonFeature in the Application/ResourceConfig subclass, (2) list the Jackson package in the web.xml of packages to scan, or (3) add the JacksonFeature to the list of providers in the web.xml

应用子类:

public class MyApplication extends ResourceConfig {  
    public MyApplication() {
        // (1)
        register(JacksonFeature.class); // <----- Jackson Support
        packages("the.package.of.your.resources");
    }
}

或 web.xml:

<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>
        org.glassfish.jersey.servlet.ServletContainer
    </servlet-class>
    <init-param>
        <!-- (2) -->
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>
            the.package.of.your.resources,
            org.codehaus.jackson.jaxrs <!-- Jackson providers -->
        </param-value>
    </init-param>
    <init-param>
        <!-- (3) -->
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>
            org.glassfish.jersey.jackson.JacksonFeature
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

在第二期"中此处查看更多详细信息.请注意,对于 ...classnames 属性,如果您要注册多个提供程序,则应将其列在以逗号、分号或换行符分隔的相同参数值中.

See more details here in the "Second Issue". Note that for the ...classnames property, if you have more than one provider to register, you should list it in the same param-value delimited with a comma, semicolon, or newline.

哦,仅供参考,ContextResolver 只是在可检索的上下文中注册 ObjectMapper,因此 MessageBodyReader/MessageBodyWriters 可以重用它.但它没有注册编组/解组所需的实际 MessageBodyReader/Writer.

Oh and just an FYI, the ContextResolver is only to register the ObjectMapper in a retrievable context, so the MessageBodyReader/MessageBodyWriters can reuse it. But it does not register the actual MessageBodyReader/Writer that is required for the marshalling/unmarshalling.