JAXB如何嵌套几个对象?

时间:2019-04-08 10:50:26

标签: java xml jaxb unmarshalling

我一直在尝试搜索操作方法,但没有找到确切要求的答案:

假设我们有这3个课程:

public class Main {
    public ArrayList<MyFirstClass> myFirstClass;
}

class MyFirstClass {
    public int num;
    public MySecondClass mySecondClass;
}

class MySecondClass {
    public String otherStr;
    public MyThirdClass myThirdClass;
}

class MyThirdClass {
    public int otherNum;
}

我希望能够使用解组器读取这些XML:

<Main>
    <MyFirstClasses>
        <MyFirstClass>
            <num>1</num>
            <MySecondClass>
                <str>Hello</str>
                <MyThirdClass>
                    <otherNum>2</otherNum>
                </MyThirdClass>
            </MySecondClass>
        </MyFirstClass>
    <MyFirstClasses>
</Main>

基本上可以在其中设置作为对象的变量(MySecond / Third Class)。

我知道我可以先使用@XMLRootElement然后使用@XmlElementWrapper(name="aName")@XmlElement(name="aName")进行

<Main>
    <MyFirstClasses>
        <MyFirstClass>
            <num>1</num>
        </MyFirstClass>
    <MyFirstClasses>
</Main>

但是我怎样才能将MySecondClass嵌套在MyFirstClass内,以便我可以设置它的值,因为否则FirstClassObject将具有一个MySecondClass,其值为空。

谢谢!

1 个答案:

答案 0 :(得分:2)

问题是您的xml与您的POJO不匹配。您可以使用注释来解决此问题(重新命名字段也可以)。试试这个:

@XmlRootElement(name = "Main")
public class Main {
    @XmlElementWrapper(name = "MyFirstClasses")
    @XmlElement(name = "MyFirstClass")
    private List<MyFirstClass> myFirstClass;
}

然后是头等舱:

@XmlAccessorType(XmlAccessType.FIELD)
public class MyFirstClass {
    private int num;
    @XmlElement(name = "MySecondClass")
    private MySecondClass mySecondClass;
}

和MySecondClass:

@XmlAccessorType(XmlAccessType.FIELD)
public class MySecondClass {
    private String str;

    @XmlElement(name = "MyThirdClass")
    private MyThirdClass myThirdClass;
}

最后是MyThirdClass:

@XmlAccessorType(XmlAccessType.FIELD)
public class MyThirdClass {
    public int otherNum;
}