How to serialize Java primitives using Jersey REST

前端 未结 6 1969
灰色年华
灰色年华 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 12:18

    Actually your best bet is to write a custom ContextResolver Provider like the following that uses natural building of JSON.

       @Provider
       public class YourContextResolver implements ContextResolver {
    
        private JAXBContext context;
        private Class[] types = { YourSpecialBean.class };
    
        public YourContextResolver() throws Exception {
            this.context = new JSONJAXBContext(
                    JSONConfiguration.natural().build(), types);
        }
    
        public JAXBContext getContext(Class objectType) {
            for (int i = 0; i < this.types.length; i++)
                if (this.types[i].equals(objectType)) return context;
    
            return null;
        }
    }
    

    The only thing special here to notice is the YourSpecialBean.class in the Class[]. This defines an array of class types that this provider will resolve naturally.

提交回复
热议问题