gpt4 book ai didi

java - JAXB如何嵌套几个对象?

转载 作者:行者123 更新时间:2023-12-02 01:33:43 25 4
gpt4 key购买 nike

我一直在尝试搜索如何执行此操作,但尚未找到满足我的确切要求的答案:

假设我们有这 3 个类(class):

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 将有一个具有 null 值的 MySecondClass。

提前致谢!

最佳答案

问题是您的 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;
}

最后我的第三堂课:

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

关于java - JAXB如何嵌套几个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55571725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com