Jersey: Json array with 1 element is serialized as object

前端 未结 8 2175
眼角桃花
眼角桃花 2021-01-03 19:20

I\'m creating a REST server with Jersey/Java and I found a strange behavior.

I have a method on the server that returns an array of objects as Json

@         


        
8条回答
  •  温柔的废话
    2021-01-03 19:52

    If you were using JAXB to build JSON result, you can configure Jersey JSON procesor to get more important JSON format.

    jersey official document has detailed config:

    To achieve more important JSON format changes, you will need to configure Jersey JSON procesor itself. Various configuration options could be set on an JSONConfiguration instance. The instance could be then further used to create a JSONConfigurated JSONJAXBContext, which serves as a main configuration point in this area. To pass your specialized JSONJAXBContext to Jersey, you will finally need to implement a JAXBContext ContextResolver:

        @Provider
    public class JAXBContextResolver implements ContextResolver {
        private final JAXBContext context;
        private final Set types;
        private Class[] ctypes = { FileInfo.class}; //your pojo class
        public JAXBContextResolver() throws Exception {
            this.types = new HashSet(Arrays.asList(ctypes));
            this.context = new JSONJAXBContext(JSONConfiguration.natural().build(),
                    ctypes); //json configuration
        }
    
        @Override
        public JAXBContext getContext(Class objectType) {
            return (types.contains(objectType)) ? context : null;
        }
    }
    

提交回复
热议问题