Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7877889
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T03:30:25+00:00 2026-06-03T03:30:25+00:00

I have a class that I would like to expose through a Jersey RESTful

  • 0

I have a class that I would like to expose through a Jersey RESTful API. It looks similar to this:

@XmlRootElement
public class Data {
    public String firstName;
    public String lastName;
}

My problem is that these fields may be null, in which case the field is omitted from the JSON output. I would like all fields to be present regardless of their value. For example, if lastName is null, the JSON output will be:

{
   "firstName" : "Oleksi"
}

instead of what I want:

{
   "firstName" : "Oleksi",
   "lastName" : null
}

I have a JAXBContextResolver (an implementation of ContextResolver) that looks like this:

@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {

     // internal state
    private final JAXBContext context;    
    private final Set<Class> types; 
    private final Class[] cTypes = { Data.class };


    public JAXBContextResolver() 
    throws Exception {

        types = new HashSet(Arrays.asList(cTypes));
        context = new JSONJAXBContext(JSONConfiguration.natural().humanReadableFormatting(true).build(), cTypes);
    }

    @Override
    public JAXBContext getContext(Class<?> objectType) {

        return (types.contains(objectType)) ? context : null;
    }
}

I’ve been trying to figure out how to get that desired output for a while, but I’ve had no luck. I’m open to trying other ContextResolvers/Serializers, but I haven’t been able to find one that works, so code examples would be nice.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T03:30:27+00:00Added an answer on June 3, 2026 at 3:30 am

    For EclipseLink JAXB (MOXy)‘s JSON binding, the correct mapping would be the following. You could try it with your provider to see if it would work also:

    @XmlRootElement
    public class Data {
        @XmlElement(nillable=true)
        public String firstName;
    
        @XmlElement(nillable=true)
        public String lastName;
    }
    

    For More Information

    • http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html
    • http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html

    UPDATE 2

    EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy’s JSON binding

    • http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html

    UPDATE 1

    The following MessageBodyReader/MessageBodyWriter may work better for you:

    import java.io.*;
    import java.lang.annotation.Annotation;
    import java.lang.reflect.*;
    import javax.xml.transform.stream.StreamSource;
    
    import javax.ws.rs.*;
    import javax.ws.rs.core.*;
    import javax.ws.rs.ext.*;
    import javax.xml.bind.*;
    
    import org.eclipse.persistence.jaxb.JAXBContextFactory;
    
    @Provider
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public class MOXyJSONProvider implements
        MessageBodyReader<Object>, MessageBodyWriter<Object>{
    
        @Context
        protected Providers providers;
    
        public boolean isReadable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
            return true;
        }
    
        public Object readFrom(Class<Object> type, Type genericType,
                Annotation[] annotations, MediaType mediaType,
                MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
                throws IOException, WebApplicationException {
                try {
                    Class<?> domainClass = getDomainClass(genericType);
                    Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller();
                    u.setProperty("eclipselink.media-type", mediaType.toString());
                    u.setProperty("eclipselink.json.include-root", false);
                    return u.unmarshal(new StreamSource(entityStream), domainClass).getValue();
                } catch(JAXBException jaxbException) {
                    throw new WebApplicationException(jaxbException);
                }
        }
    
        public boolean isWriteable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
            return true;
        }
    
        public void writeTo(Object object, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, Object> httpHeaders,
            OutputStream entityStream) throws IOException,
            WebApplicationException {
            try {
                Class<?> domainClass = getDomainClass(genericType);
                Marshaller m = getJAXBContext(domainClass, mediaType).createMarshaller();
                m.setProperty("eclipselink.media-type", mediaType.toString());
                m.setProperty("eclipselink.json.include-root", false);
                m.marshal(object, entityStream);
            } catch(JAXBException jaxbException) {
                throw new WebApplicationException(jaxbException);
            }
        }
    
        public long getSize(Object t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
            return -1;
        }
    
        private JAXBContext getJAXBContext(Class<?> type, MediaType mediaType)
            throws JAXBException {
            ContextResolver<JAXBContext> resolver
                = providers.getContextResolver(JAXBContext.class, mediaType);
            JAXBContext jaxbContext;
            if(null == resolver || null == (jaxbContext = resolver.getContext(type))) {
                return JAXBContextFactory.createContext(new Class[] {type}, null); 
            } else {
                return jaxbContext;
            }
        }
    
        private Class<?> getDomainClass(Type genericType) {
            if(genericType instanceof Class) {
                return (Class<?>) genericType;
            } else if(genericType instanceof ParameterizedType) {
                return (Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[0];
            } else {
                return null;
            }
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a domain model that includes something like this: public class Customer :
I have a class that I would like to use in a scala.collection.mutable.PriorityQueue, but
I have a class in silverlight that I would like to store to disk.
I have a class that is marked with DataContract attributes and I would like
I have a class that is called regularly by several objects. I would like
I have a class that contains decoded video frames. I would like my decoder
I have a custom-made view that extends the View class. I would like 2
I have written a service that I would like expose both via rest and
I have a class member in an ActionScript 3 class that looks something like
I want to have an class like this, public class Apple { public string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.