Jersey serialize empty list and single element list as an array

By : Wijden
Source: Stackoverflow.com
Question!

Since there is a probelm with serialization an emplty list and single element list in Jersey. I tried to fix it by adding JAXBContextResolver class. The goal is to return JSON object thant contains JSON array to my Android application in all cases (if it returns 0 element or 1 element or more than 1). But my JSON data don't look the same. And I get an error in my android application Expected BEGIN_OBJECT but was BEGIN_ARRAY I would greatly appreciate your help. Thanks in advance

@Provider
    public class JAXBContextResolver implements ContextResolver<JAXBContext> {
        private JAXBContext context;
        private final Set<Class> types;

        // pojo class
        private Class[] ctypes = { Workitem.class, Project.class, User.class };

        public JAXBContextResolver() throws Exception {
            NaturalBuilder builder = JSONConfiguration.natural();
            //assure the rootelement name appears in the json structure
            builder.rootUnwrapping(false); 
            this.types = new HashSet(Arrays.asList(ctypes));
            // json configuration
            this.context = new JSONJAXBContext(builder.build(), ctypes);
        }

        @Override
        public JAXBContext getContext(Class<?> objectType) {
            return (types.contains(objectType)) ? context : null;
        }

    }

My JSON data look like this when I set builder.rootUnwrapping(true);

[
    {
        "assignedTo": "assignee1",
        "businessKey": "Key1",
        "createdBy": "createdBy1",
        "description": "description1"
    }
]

But I want it to be like this to solve my problem in Android side :

{
    "project": [
        {
            "assignedTo": "assignee1",
            "businessKey": "Key1",
            "createdBy": "createdBy1",
            "description": "description1"
        }
    ]
}

I added @JsonRootName(value = "project") to my My Project class in order to fix my problem but I get this error but I don't khow how to solve it please I need help

Multiple markers at this line
    - JsonRootName cannot be resolved to a type
    - The attribute value is undefined for the annotation type JsonRootName

My Project class is like this :

@XmlRootElement
@JsonRootName(value = "project")

public class Project implements Serializable {

    private static final long serialVersionUID = 1L;


    private String description;
    private String businessKey;
    private String createdBy;
        private String assignedTo;

    public Project() {
    }
// getter and setter method

}
By : Wijden


Answers
Try to change the annotation of your Project class as

@JsonRootName(value = "rootname")


This video can help you solving your question :)
By: admin