Jersey将空列表和单个元素列表序列化为数组

时间:2013-05-21 15:49:15

标签: java android json jaxb jersey

由于在泽西岛有一个带有序列化问题的问题列表和单个元素列表。我试图通过添加JAXBContextResolver类来修复它。目标是在所有情况下将包含JSON数组的JSON对象返回到我的Android应用程序(如果它返回0个元素或1个元素或多于1个)。但是我的JSON数据看起来并不一样。我的Android应用程序Expected BEGIN_OBJECT but was BEGIN_ARRAY出错了 非常感谢你的帮助。提前致谢

@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;
        }

    }

当我设置builder.rootUnwrapping(true);

时,我的JSON数据看起来像这样
[
    {
        "assignedTo": "assignee1",
        "businessKey": "Key1",
        "createdBy": "createdBy1",
        "description": "description1"
    }
]

但是我希望它能解决我在Android方面遇到的问题:

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

我将@JsonRootName(value = "project")添加到我的My Project类中以解决我的问题,但我收到此错误但我不知道如何解决它请我需要帮助

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

我的Project类是这样的:

@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

}

1 个答案:

答案 0 :(得分:0)

尝试将Project类的注释更改为

@JsonRootName(value = "rootname")