Using jaxb to represent a list as the root element

▼魔方 西西 提交于 2019-12-23 16:13:58

问题


How can we marshal/unmarshal the root element in a JSON that contains a list using JAXB?

So it would the JSON as

{
    "tag" : [
        {
            "id" : "a",
            "id2": "aa" 
        },
        {
            "id" : "b",
            "id2" : "bb" 
        },
        {
            "id" : "c",
            "id2" : "cc" 
        } 
    ] 
}

I am using Apache CXF which supports JSON through Jettison.

The Java class could look like the one below. One could use a XmlList annotation for the list, and XmlValue for having that list in the root element. The problem is XmlValue would not take a user-defined type.

@XmlRootElement(name = "tag")
public class test
{
    @XmlList
    @XmlValue
    private List<UserDefinedType> testList;
}

Is there a way to get around this. I need this to work for un-marshalling an incoming JSON. Got this idea from here http://bdoughan.blogspot.com/2010/09/jaxb-collection-properties.html


回答1:


This should work for the JSON format you mentioned. However, it might not work if you want to marshall/unmarshall to a certain XML format too.

@XmlRootElement
public class Test {
    @XmlElement(name = "tag")
    private List<UserDefinedType> testList;
}

public class UserDefinedType {
    @XmlElement(name = "id")
    private String someId;

    @XmlElement(name = "id2")
    private String someId2;
}



回答2:


This worked for me. The names of the XmlRootElement and the list are the same.

@XmlRootElement(name = "tag")
@XmlAccessorType(XmlAccessType.FIELD)
public class Test {
    @XmlElement(name = "tag")
    public List<UserDefinedType> testList;
}

@XmlAccessorType(XmlAccessType.FIELD)
public class UserDefinedType {
    @XmlElement(name = "id")
    public String someId;

    @XmlElement(name = "id2")
    public String someId2;
}


来源:https://stackoverflow.com/questions/4729385/using-jaxb-to-represent-a-list-as-the-root-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!