I Needed to configure Jackson’s JSON library for Glassfish 4.1 and was getting errors due to another library (MOXY) being used. This article is about how to fix the Jackson error.
First, we implement the javax.ws.rs.core.Feature interface:
public class JacksonFeature implements Feature {
Logger L = LoggerFactory.getLogger(JacksonFeature.class);
@Override
public boolean configure(final FeatureContext context) {
String postfix = "";
postfix = '.' + context.getConfiguration().getRuntimeType().name().toLowerCase();
context.property(CommonProperties.MOXY_JSON_FEATURE_DISABLE + postfix, true);
L.info("Set property to true disable MOXY: " + CommonProperties.MOXY_JSON_FEATURE_DISABLE + postfix);
context.register(JsonParseExceptionMapper.class);
context.register(JsonMappingExceptionMapper.class);
context.register(JacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
return true;
}
}
Next, we configure our web service by extending the ResourceConfig class provided by Glassfish.
@javax.ws.rs.ApplicationPath("api")
public classMyResourceConfig extends ResourceConfig {
publicMyServicesResourceConfig() {
register( new GZipEncoder() );
register( JacksonFeature.class );
addMyResources();
}
private void addMyResources() {
register( Service1.class );
register( Service2.class );
}
}
There is also a package(‘net.my.package’) to register a bunch of services.
Here we can see some test code:
@Test
public void testJF() {
// name().toLowerCase()
RuntimeType rt = RuntimeType.SERVER;
// getRuntimeType()
Configuration c = mock(Configuration.class);
when(c.getRuntimeType()).thenReturn(rt);
// context.getConfiguration()
FeatureContext fc = mock(FeatureContext.class);
when(fc.getConfiguration()).thenReturn(c);
try {
jf = new JacksonFeature();
jf.configure(fc);
} catch (Exception e) {
fail("Caught exception: " + e.getMessage());
}
}