force glassfish 4 to use jackson 2.3

落爺英雄遲暮 提交于 2019-12-03 16:23:44

First make sure you have the following in your pom.xml:

    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>${jackson.version}</version>
    </dependency>

Then make sure you DO NOT have this in any pom.xml:

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

Then you need to disable moxy. The easiest way to do this is to ditch your Application class and replace is with a ResourceConfig class. First lets create YOUR JacksonFeature class:

    public class JacksonFeature implements Feature {

        public boolean configure( final FeatureContext context ) {

            String postfix = '.' + context.getConfiguration().getRuntimeType().name().toLowerCase();

            context.property( CommonProperties.MOXY_JSON_FEATURE_DISABLE + postfix, true );

            context.register( JsonParseExceptionMapper.class );
            context.register( JsonMappingExceptionMapper.class );
            context.register( JacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class );

            return true;
        }
    }

Two interesting things here, first I disabled moxy and second I made sure to add the JacksonException mappers. This way you will get better errors than internal server error if there is a parsing or generation exception. Okay, last step it so rewrite your Application as a ResourceConfig class:

@javax.ws.rs.ApplicationPath("resources")
public class RestApplication extends ResourceConfig {

    public RestApplication() {
        register( new GZipEncoder() );
        register( JacksonFeature.class );
    }

    private void addMyResources() {
        register( MyResource1.class );
        register( MyResource2.class );
    }
}

That should do it. Also, instead of registering the resources one by one like this, if you know their path you can just remove all that code and add this to the constructor of RestApplication:

package( "com.me.myrestresourcespackage" );

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!