【问题标题】:Jersey serialize empty list and single element list as an arrayJersey将空列表和单元素列表序列化为数组
【发布时间】:2013-05-21 15:49:14
【问题描述】:

由于在 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") 添加到我的“我的项目”课程中以解决我的问题,但我收到此错误但我不知道如何解决它,请我需要帮助

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

我的项目类是这样的:

@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

}

【问题讨论】:

    标签: java android json jaxb jersey


    【解决方案1】:

    尝试将您的项目类的注释更改为

    @JsonRootName(value = "rootname")
    

    【讨论】:

    • 我收到此错误:- JsonRootName 无法解析为类型 - 注释类型 JsonRootName 的属性值未定义
    • 我仍然无法解决我的问题,我需要帮助。
    猜你喜欢
    • 2012-01-03
    • 1970-01-01
    • 2021-11-22
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2016-12-29
    相关资源
    最近更新 更多