Class MOXyJsonProvider

  • All Implemented Interfaces:
    javax.ws.rs.ext.MessageBodyReader<java.lang.Object>, javax.ws.rs.ext.MessageBodyWriter<java.lang.Object>

    @Produces({"application/json","*/*","application/x-javascript"})
    @Consumes({"application/json","*/*"})
    @Provider
    public class MOXyJsonProvider
    extends java.lang.Object
    implements javax.ws.rs.ext.MessageBodyReader<java.lang.Object>, javax.ws.rs.ext.MessageBodyWriter<java.lang.Object>

    This is an implementation of MessageBodyReader/MessageBodyWriter that can be used to enable EclipseLink JAXB (MOXy) as the JSON provider.

    Supported Media Type Patterns

    • */json (i.e. application/json and text/json)
    • */*+json

    Below are some different usage options.

    Option #1 - MOXyJsonProvider Default Behavior

    You can use the Application class to specify that MOXyJsonProvider should be used with your JAX-RS application.

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

    You can use the Application class to specify a configured instance of MOXyJsonProvider should be used with your JAX-RS application.

     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.setFormattedOutput(true);
             moxyJsonProvider.setIncludeRoot(true);
    
             HashSet<Object> set = new HashSet<Object>(2);
             set.add(moxyJsonProvider);
             return set;
         }
    
     }
     
    Option #3 - Extend MOXyJsonProvider

    You can use MOXyJsonProvider for creating your own MessageBodyReader/MessageBodyWriter.

     package org.example;
    
     import java.lang.annotation.Annotation;
     import java.lang.reflect.Type;
    
     import javax.ws.rs.*;
     import javax.ws.rs.core.*;
     import javax.ws.rs.ext.Provider;
     import javax.xml.bind.*;
    
     import org.eclipse.persistence.jaxb.MarshallerProperties;
     import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
    
     @Provider
     @Produces(MediaType.APPLICATION_JSON)
     @Consumes(MediaType.APPLICATION_JSON)
     public class CustomerJSONProvider extends MOXyJsonProvider {
    
         @Override
         public boolean isReadable(Class<?> type, Type genericType,
                 Annotation[] annotations, MediaType mediaType) {
             return getDomainClass(genericType) == Customer.class;
         }
    
         @Override
         public boolean isWriteable(Class<?> type, Type genericType,
                 Annotation[] annotations, MediaType mediaType) {
             return isReadable(type, genericType, annotations, mediaType);
         }
    
         @Override
         protected void preReadFrom(Class<Object> type, Type genericType,
                 Annotation[] annotations, MediaType mediaType,
                 MultivaluedMap<String, String> httpHeaders,
                 Unmarshaller unmarshaller) throws JAXBException {
             unmarshaller.setProperty(MarshallerProperties.JSON_VALUE_WRAPPER, "$");
         }
    
         @Override
         protected void preWriteTo(Object object, Class<?> type, Type genericType,
                 Annotation[] annotations, MediaType mediaType,
                 MultivaluedMap<String, Object> httpHeaders, Marshaller marshaller)
                 throws JAXBException {
             marshaller.setProperty(MarshallerProperties.JSON_VALUE_WRAPPER, "$");
         }
    
     }
     
    Since:
    2.4
    • Field Summary

      Fields 
      Modifier and Type Field Description
      protected javax.ws.rs.ext.Providers providers  
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      java.lang.String getAttributePrefix()
      The value that will be prepended to all keys that are mapped to an XML attribute.
      java.lang.Class<?> getDomainClass​(java.util.Set<java.lang.Class<?>> domainClasses)
      Get first non java class if exists.
      protected java.util.Set<java.lang.Class<?>> getDomainClasses​(java.lang.reflect.Type genericType)
      A convenience method to get the domain class (i.e.
      protected JAXBContext getJAXBContext​(java.util.Set<java.lang.Class<?>> domainClasses, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType, javax.ws.rs.core.MultivaluedMap<java.lang.String,​?> httpHeaders)
      Return the JAXBContext that corresponds to the domain class.
      java.util.Map<java.lang.String,​java.lang.String> getNamespacePrefixMapper()
      By default the JSON-binding will ignore namespace qualification.
      char getNamespaceSeparator()
      This character (default is '.') separates the prefix from the key name.
      long getSize​(java.lang.Object t, java.lang.Class<?> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType)  
      java.lang.String getValueWrapper()
      The key that will correspond to the property mapped with @XmlValue.
      boolean isFormattedOutput()  
      boolean isIncludeRoot()  
      boolean isMarshalEmptyCollections()
      If true empty collections will be marshalled as empty arrays, else the collection will not be marshalled to JSON (default is true).
      boolean isReadable​(java.lang.Class<?> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType)  
      boolean isWrapperAsArrayName()
      If true the grouping element will be used as the JSON key.
      boolean isWriteable​(java.lang.Class<?> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType)  
      protected void preReadFrom​(java.lang.Class<java.lang.Object> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType, javax.ws.rs.core.MultivaluedMap<java.lang.String,​java.lang.String> httpHeaders, Unmarshaller unmarshaller)
      Subclasses of MOXyJsonProvider can override this method to customize the instance of Unmarshaller that will be used to unmarshal the JSON message in the readFrom call.
      protected void preWriteTo​(java.lang.Object object, java.lang.Class<?> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType, javax.ws.rs.core.MultivaluedMap<java.lang.String,​java.lang.Object> httpHeaders, Marshaller marshaller)
      Subclasses of MOXyJsonProvider can override this method to customize the instance of Marshaller that will be used to marshal the domain objects to JSON in the writeTo call.
      java.lang.Object readFrom​(java.lang.Class<java.lang.Object> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType, javax.ws.rs.core.MultivaluedMap<java.lang.String,​java.lang.String> httpHeaders, java.io.InputStream entityStream)  
      void setAttributePrefix​(java.lang.String attributePrefix)
      Specify a value that will be prepended to all keys that are mapped to an XML attribute.
      void setFormattedOutput​(boolean formattedOutput)
      Specify if the JSON output should be formatted (default is false).
      void setIncludeRoot​(boolean includeRoot)
      Specify if the root node should be included in the JSON message (default is false).
      void setMarshalEmptyCollections​(boolean marshalEmptyCollections)
      If true empty collections will be marshalled as empty arrays, else the collection will not be marshalled to JSON (default is true).
      void setNamespacePrefixMapper​(java.util.Map<java.lang.String,​java.lang.String> namespacePrefixMapper)
      By default the JSON-binding will ignore namespace qualification.
      void setNamespaceSeparator​(char namespaceSeparator)
      This character (default is '.') separates the prefix from the key name.
      void setValueWrapper​(java.lang.String valueWrapper)
      Specify the key that will correspond to the property mapped with @XmlValue.
      void setWrapperAsArrayName​(boolean wrapperAsArrayName)
      If true the grouping element will be used as the JSON key.
      protected boolean supportsMediaType​(javax.ws.rs.core.MediaType mediaType)  
      void writeTo​(java.lang.Object object, java.lang.Class<?> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType, javax.ws.rs.core.MultivaluedMap<java.lang.String,​java.lang.Object> httpHeaders, java.io.OutputStream entityStream)  
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • providers

        @Context
        protected javax.ws.rs.ext.Providers providers
    • Constructor Detail

      • MOXyJsonProvider

        public MOXyJsonProvider()
    • Method Detail

      • getDomainClasses

        protected java.util.Set<java.lang.Class<?>> getDomainClasses​(java.lang.reflect.Type genericType)
        A convenience method to get the domain class (i.e. Customer or Foo, Bar) from the parameter/return type (i.e. Customer, List<Customer>, JAXBElement<Customer>, JAXBElement<? extends Customer>, List<JAXBElement<Customer>>, or List<JAXBElement<? extends Customer>> List<Foo<Bar>>).
        Parameters:
        genericType - - The parameter/return type of the JAX-RS operation.
        Returns:
        The corresponding domain classes.
      • getJAXBContext

        protected JAXBContext getJAXBContext​(java.util.Set<java.lang.Class<?>> domainClasses,
                                             java.lang.annotation.Annotation[] annotations,
                                             javax.ws.rs.core.MediaType mediaType,
                                             javax.ws.rs.core.MultivaluedMap<java.lang.String,​?> httpHeaders)
                                      throws JAXBException
        Return the JAXBContext that corresponds to the domain class. This method does the following:
        1. If an EclipseLink JAXB (MOXy) JAXBContext is available from a ContextResolver then use it.
        2. If an existing JAXBContext was not found in step one, then create a new one on the domain class.
        Parameters:
        domainClasses - - The domain classes we need a JAXBContext for.
        annotations - - The annotations corresponding to domain object.
        mediaType - - The media type for the HTTP entity.
        httpHeaders - - HTTP headers associated with HTTP entity.
        Returns:
        Throws:
        JAXBException
      • getSize

        public long getSize​(java.lang.Object t,
                            java.lang.Class<?> type,
                            java.lang.reflect.Type genericType,
                            java.lang.annotation.Annotation[] annotations,
                            javax.ws.rs.core.MediaType mediaType)
        Specified by:
        getSize in interface javax.ws.rs.ext.MessageBodyWriter<java.lang.Object>
      • isFormattedOutput

        public boolean isFormattedOutput()
        Returns:
        true if the JSON output should be formatted (default is false).
      • isMarshalEmptyCollections

        public boolean isMarshalEmptyCollections()
        If true empty collections will be marshalled as empty arrays, else the collection will not be marshalled to JSON (default is true).
        See Also:
        MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS
      • isReadable

        public boolean isReadable​(java.lang.Class<?> type,
                                  java.lang.reflect.Type genericType,
                                  java.lang.annotation.Annotation[] annotations,
                                  javax.ws.rs.core.MediaType mediaType)
        Specified by:
        isReadable in interface javax.ws.rs.ext.MessageBodyReader<java.lang.Object>
        Returns:
        true indicating that MOXyJsonProvider will be used for the JSON binding if the media type is of the following patterns */json or */*+json, and the type is not assignable from any of (or a Collection or JAXBElement of) the following:
        • byte[]
        • java.io.File
        • java.io.InputStream
        • java.io.Reader
        • java.lang.Object
        • java.lang.String
        • javax.activation.DataSource
      • isWrapperAsArrayName

        public boolean isWrapperAsArrayName()
        If true the grouping element will be used as the JSON key.

        Example

        Given the following class:

         @XmlAccessorType(XmlAccessType.FIELD)
         public class Customer {
        
             @XmlElementWrapper(name="phone-numbers")
             @XmlElement(name="phone-number")
             private List<PhoneNumber> phoneNumbers;
        
         }
         

        If the property is set to false (the default) the JSON output will be:

         {
             "phone-numbers" : {
                 "phone-number" : [ {
                     ...
                 }, {
                     ...
                 }]
             }
         }
         

        And if the property is set to true, then the JSON output will be:

         {
             "phone-numbers" : [ {
                 ...
             }, {
                 ...
             }]
         }
         
        See Also:
        JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME
        Since:
        2.4.2
      • isWriteable

        public boolean isWriteable​(java.lang.Class<?> type,
                                   java.lang.reflect.Type genericType,
                                   java.lang.annotation.Annotation[] annotations,
                                   javax.ws.rs.core.MediaType mediaType)
        Specified by:
        isWriteable in interface javax.ws.rs.ext.MessageBodyWriter<java.lang.Object>
        Returns:
        true indicating that MOXyJsonProvider will be used for the JSON binding if the media type is of the following patterns */json or */*+json, and the type is not assignable from any of (or a Collection or JAXBElement of) the following:
        • byte[]
        • java.io.File
        • java.lang.Object
        • java.lang.String
        • javax.activation.DataSource
        • javax.ws.rs.core.StreamingOutput
      • preReadFrom

        protected void preReadFrom​(java.lang.Class<java.lang.Object> type,
                                   java.lang.reflect.Type genericType,
                                   java.lang.annotation.Annotation[] annotations,
                                   javax.ws.rs.core.MediaType mediaType,
                                   javax.ws.rs.core.MultivaluedMap<java.lang.String,​java.lang.String> httpHeaders,
                                   Unmarshaller unmarshaller)
                            throws JAXBException
        Subclasses of MOXyJsonProvider can override this method to customize the instance of Unmarshaller that will be used to unmarshal the JSON message in the readFrom call.
        Parameters:
        type - - The Class to be unmarshalled (i.e. Customer or List)
        genericType - - The type of object to be unmarshalled (i.e Customer or List<Customer>).
        annotations - - The annotations corresponding to domain object.
        mediaType - - The media type for the HTTP entity.
        httpHeaders - - HTTP headers associated with HTTP entity.
        unmarshaller - - The instance of Unmarshaller that will be used to unmarshal the JSON message.
        Throws:
        JAXBException
        See Also:
        UnmarshallerProperties
      • preWriteTo

        protected void preWriteTo​(java.lang.Object object,
                                  java.lang.Class<?> type,
                                  java.lang.reflect.Type genericType,
                                  java.lang.annotation.Annotation[] annotations,
                                  javax.ws.rs.core.MediaType mediaType,
                                  javax.ws.rs.core.MultivaluedMap<java.lang.String,​java.lang.Object> httpHeaders,
                                  Marshaller marshaller)
                           throws JAXBException
        Subclasses of MOXyJsonProvider can override this method to customize the instance of Marshaller that will be used to marshal the domain objects to JSON in the writeTo call.
        Parameters:
        object - - The domain object that will be marshalled to JSON.
        type - - The Class to be marshalled (i.e. Customer or List)
        genericType - - The type of object to be marshalled (i.e Customer or List<Customer>).
        annotations - - The annotations corresponding to domain object.
        mediaType - - The media type for the HTTP entity.
        httpHeaders - - HTTP headers associated with HTTP entity.
        marshaller - - The instance of Marshaller that will be used to marshal the domain object to JSON.
        Throws:
        JAXBException
        See Also:
        MarshallerProperties
      • readFrom

        public java.lang.Object readFrom​(java.lang.Class<java.lang.Object> type,
                                         java.lang.reflect.Type genericType,
                                         java.lang.annotation.Annotation[] annotations,
                                         javax.ws.rs.core.MediaType mediaType,
                                         javax.ws.rs.core.MultivaluedMap<java.lang.String,​java.lang.String> httpHeaders,
                                         java.io.InputStream entityStream)
                                  throws java.io.IOException,
                                         javax.ws.rs.WebApplicationException
        Specified by:
        readFrom in interface javax.ws.rs.ext.MessageBodyReader<java.lang.Object>
        Throws:
        java.io.IOException
        javax.ws.rs.WebApplicationException
      • getDomainClass

        public java.lang.Class<?> getDomainClass​(java.util.Set<java.lang.Class<?>> domainClasses)
        Get first non java class if exists.
        Parameters:
        domainClasses -
        Returns:
        first domain class or first generic class or just the first class from the list
      • setFormattedOutput

        public void setFormattedOutput​(boolean formattedOutput)
        Specify if the JSON output should be formatted (default is false).
        Parameters:
        formattedOutput - - true if the output should be formatted, else false.
      • setMarshalEmptyCollections

        public void setMarshalEmptyCollections​(boolean marshalEmptyCollections)
        If true empty collections will be marshalled as empty arrays, else the collection will not be marshalled to JSON (default is true).
        See Also:
        MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS
      • setNamespacePrefixMapper

        public void setNamespacePrefixMapper​(java.util.Map<java.lang.String,​java.lang.String> namespacePrefixMapper)
        By default the JSON-binding will ignore namespace qualification. If this property is set then a prefix corresponding to the namespace URI and a namespace separator will be prefixed to the key. include it you can specify a Map of namespace URI to prefix.
        See Also:
        MarshallerProperties.NAMESPACE_PREFIX_MAPPER, UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER
      • setWrapperAsArrayName

        public void setWrapperAsArrayName​(boolean wrapperAsArrayName)
        If true the grouping element will be used as the JSON key.

        Example

        Given the following class:

         @XmlAccessorType(XmlAccessType.FIELD)
         public class Customer {
        
             @XmlElementWrapper(name="phone-numbers")
             @XmlElement(name="phone-number")
             private List<PhoneNumber> phoneNumbers;
        
         }
         

        If the property is set to false (the default) the JSON output will be:

         {
             "phone-numbers" : {
                 "phone-number" : [ {
                     ...
                 }, {
                     ...
                 }]
             }
         }
         

        And if the property is set to true, then the JSON output will be:

         {
             "phone-numbers" : [ {
                 ...
             }, {
                 ...
             }]
         }
         
        See Also:
        JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME
        Since:
        2.4.2
      • supportsMediaType

        protected boolean supportsMediaType​(javax.ws.rs.core.MediaType mediaType)
        Returns:
        true for all media types of the pattern */json and */*+json.
      • writeTo

        public void writeTo​(java.lang.Object object,
                            java.lang.Class<?> type,
                            java.lang.reflect.Type genericType,
                            java.lang.annotation.Annotation[] annotations,
                            javax.ws.rs.core.MediaType mediaType,
                            javax.ws.rs.core.MultivaluedMap<java.lang.String,​java.lang.Object> httpHeaders,
                            java.io.OutputStream entityStream)
                     throws java.io.IOException,
                            javax.ws.rs.WebApplicationException
        Specified by:
        writeTo in interface javax.ws.rs.ext.MessageBodyWriter<java.lang.Object>
        Throws:
        java.io.IOException
        javax.ws.rs.WebApplicationException
        See Also:
        MessageBodyWriter.writeTo(java.lang.Object, java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap, java.io.OutputStream)