Using third-party entity provider frameworks with Jersey

We discussed the various frameworks for JSON processing (and binding) in Chapter 2, Java APIs for JSON Processing. In this section, we will see how to tell the JAX-RS runtime to use a different entity provider framework (also known as the binding framework) instead of the default one provided by the container.

When you deploy the JAX-RS 2.0 application on the WebLogic or GlassFish server, the runtime automatically adds MOXy as the JSON binding framework for your application. Note that MOXy is EclipseLink's object-to-XML and object-to-JSON mapping provider. However, you can override the default JSON processor framework offered by the Jersey runtime with one that you may prefer for your application.

The following example overrides the default JSON framework used in the Jersey implementation with Jackson (https://github.com/FasterXML/jackson):

  1. The first step is to add a dependency to the JSON processor framework that you want to use. For instance, to use Jackson, you need to add the jackson-jaxrs-json-provider and jackson-databind JAR files to the application.
  2. Jersey allows you to disable the MOXy JSON framework by setting the jersey.config.disableMoxyJson configuration property to true. You can do this by overriding javax.ws.rs.core.Application::getProperties(). This is shown in the code snippet given towards the end of this section.
  3. The next step is to register the Provider class. You can register the provider class as a singleton, as this provider does not hold any state.

The following code snippet shows a configuration that you will need to make in the Application subclass to use JacksonJsonProvider as the JSON binding framework:

//Other imports are omitted for brevity 
import javax.ws.rs.core.Application; 
import javax.ws.rs.ext.Provider;  
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; 
 
@javax.ws.rs.ApplicationPath("webresources") 
public class HRApplication extends Application { 
 
    @Override 
    public Set<Class<?>> getClasses() { 
        Set<Class<?>> resources = new java.util.HashSet<>(); 
        resources.add(HRService.class); 
        return resources; 
    } 
 
   @Override 
    public Set<Object> getSingletons() { 
        Set<Object> set = new HashSet<>(); 
       // Register JacksonJsonProvider as a singleton  
       // to allow reuse of ObjectMapper: 
        set.add( 
           new com.fasterxml.jackson.jaxrs.json. 
           JacksonJsonProvider()); 
        return set; 
    } 
 
    @Override 
    public Map<String, Object> getProperties() { 
        Map<String, Object> map = new HashMap<>(); 
        //Disables configuration of MOXy Json feature. 
        map.put("jersey.config.disableMoxyJson.server", true); 
        return map; 
    } 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.21.152