Customizing JSON marhsalling with GlassFish v4

落花浮王杯 提交于 2019-11-29 10:51:12
Paul Samsotha

Glassfish uses MOXy as the default provider. Internally it has the libraries to handle Jackson, Jettison, and MOXy, but the default is MOXy. There are two ways to disable MOXy

  1. Set the Jersey property jersey.config.server.disableMoxyJson to true.
  2. Register a different XxxJsonFeature that disables MOXy. For instance the JacksonFeature that comes with jersey-media-json-jackson

Note that Glassfish comes with a Jackson provider, but it is Jackson 1.x. If you want to use 2.x, instead of the using the jersey-media-json-jackson dependency listed above, it would be better to use the underlying Jackson provider dependency, which is

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

You can register the JacksonJsonProvider or the JacksonJaxbJsonProvider for JAXB annotation support.

To configure Jackson, the easiest way to implement a ContextResolver, as seen in this answer. The JacksonJsonProvider will lookup this ContextResolver to retrieve the ObjectMapper used for (de)serialization.

You will also need to remember to disable MOXy, as mentioned above.

Also one thing to note is that this solution is portable. With JAX-RS, the only portable application configuration is through an Application subclass

@ApplicationPath("/api")
public class MyApplication extends Application {}

That being said, the disabling of MOXy in the case of Glassfish, is nothing more than setting a property. In the Application class, you can override getProperties() which returns a Map<String, Object>. This is where you can set the property. And because it s nothing more than a String (no outside dependencies), it remains portable

@ApplicationPath("/api")
public class MyApplication extends Application {
    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> props = new HashMap<>();
        props.put("jersey.config.server.disableMoxyJson", true);
        return props;
    }
}

As far as the above Jackson dependency, it is also a portable solution. It it nothing (JAX-RS) implementation specific. It implements and uses standard JAX-RS APIs

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