Search code examples
javajsonweb-servicesmoxyjersey-2.0

Jersey 2.0 equivalent to POJOMappingFeature


I have some experience using Jersey < 2.0. Now I am trying to build a war application to provide a JSON Webservice API.

I am now struggling for a considerable amount of time trying to configure Moxy and it seams to be way more complicated than what was adding

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

to your web.xml back in Jersey < 2.0.

Is there some possibility to just say "please add json support"?

Currently I just get a lot of Internal Server Error errors without any log entries on the server and just think "I have to do something totally wrong, this can't be so hard"

Can anyone give me a hint?


Solution

  • You can configure EclipseLink MOXy as the JSON-binding provider by configuring the MOXyJsonProvider class through a JAX-RS Application class.

    Example #1

    package org.example;
    
    import java.util.*;
    import javax.ws.rs.core.Application;
    import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
    
    public class CustomerApplication  extends Application {
    
        @Override
        public Set<Class<?>> getClasses() {
            HashSet<Class<?>> set = new HashSet<Class<?>>(2);
            set.add(MOXyJsonProvider.class);
            set.add(CustomerService.class);
            return set;
        }
    
    }
    

    Example #2

    package org.example;
    
    import java.util.*;
    import javax.ws.rs.core.Application;
    import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
    
    public class CustomerApplication  extends Application {
    
        @Override
        public Set<Class<?>> getClasses() {
            HashSet<Class<?>> set = new HashSet<Class<?>>(1);
            set.add(ExampleService.class);
            return set;
        }
    
        @Override
        public Set<Object> getSingletons() {
            MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider();
    
            moxyJsonProvider.setAttributePrefix("@");
            moxyJsonProvider.setFormattedOutput(true);
            moxyJsonProvider.setIncludeRoot(true);
            moxyJsonProvider.setMarshalEmptyCollections(false);
            moxyJsonProvider.setValueWrapper("$");
    
            Map<String, String> namespacePrefixMapper = new HashMap<String, String>(1);
            namespacePrefixMapper.put("http://www.example.org/customer", "cust");
            moxyJsonProvider.setNamespacePrefixMapper(namespacePrefixMapper);
            moxyJsonProvider.setNamespaceSeparator(':');
    
            HashSet<Object> set = new HashSet<Object>(1);
            set.add(moxyJsonProvider);
            return set;
        }
    
    } 
    

    For More Information