How to serialize Java primitives using Jersey REST

前端 未结 6 1971
灰色年华
灰色年华 2020-11-29 11:47

In my application I use Jersey REST to serialize complex objects. This works quite fine. But there are a few method which simply return an int or boolean.

Jersey can

6条回答
  •  情话喂你
    2020-11-29 11:55

    I had the same problem today and didn't give up until i found a really good suitable solution. I can not update the jersey library from 1.1.5 it is a Legacy System. My Rest Service returns a List and they should follow those rules.

    1. Empty Lists are rendered as [] (almost impossible)
    2. One Element Lists are rendered as [] (difficult but only mapping configuration)
    3. Many Element Lists are rendered as [] (easy)

    Start from easy to impossible.

    3) nothing today normal JSON Mapping

    2) Register JAXBContextResolver like the following

    @Provider
    public class JAXBContextResolver implements ContextResolver {
        private final JAXBContext context;
        private final Set> types;
        private Class[] ctypes = { Pojo.class }; //your pojo class
        public JAXBContextResolver() throws Exception {
            this.types = new HashSet>(Arrays.asList(ctypes));
            this.context = new JSONJAXBContext(JSONConfiguration.mapped()
                    .rootUnwrapping(true)
                    .arrays("propertyName") //that should rendered as JSONArray even if the List only contain one element but doesn't handle the empty Collection case
                    .build()
                    , ctypes);
        }
    
        @Override
        public JAXBContext getContext(Class objectType) {
            return (types.contains(objectType)) ? context : null;
        }
    }
    

    1) The following approach only works for Collections$EmptyList class. May you find a way to make it general for all Collections they are empty. May code deal with EmptyList so.

    @Provider
    @Produces(value={MediaType.APPLICATION_JSON})
    public class EmptyListWriter implements MessageBodyWriter {
    
        private static final String EMPTY_JSON_ARRAY = "[]";
    
        @Override
        public long getSize(AbstractList list, Class clazz, Type type, Annotation[] annotations, MediaType mediaType) {
            return EMPTY_JSON_ARRAY.length();
        }
    
        @Override
        public boolean isWriteable(Class clazz, Type type, Annotation[] annotations, MediaType mediaType) {
            return clazz.getName().equals("java.util.Collections$EmptyList");
        }
    
        @Override
        public void writeTo(AbstractList list, Class clazz, Type type, Annotation[] annotations, MediaType mediaType, 
                MultivaluedMap headers, OutputStream outputStream) throws IOException, WebApplicationException {
            if (list.isEmpty())
                outputStream.write(EMPTY_JSON_ARRAY.getBytes());            
        }
    }
    

提交回复
热议问题