gpt4 book ai didi

java - JAXB 将 1 个 XML 标记映射到 2 个变量

转载 作者:行者123 更新时间:2023-11-30 10:41:49 24 4
gpt4 key购买 nike

我正在尝试使用一个类来映射我从 XML 请求中获得的响应。但 xml 响应不同,具体取决于自己的一些设置。例如,在响应中我得到标签“所有者”,其中填充了所有者对象的 ID。如果我在我的请求中添加设置,我将取回完整的所有者数据,例如名字和姓氏。现在我想根据响应将所有者标记映射到字符串变量或类。

示例:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "domain")
public class Response {

@XmlElement
private String name;

@XmlElement(name = "owner")
private String ownerSimple;

@XmlElement(name = "owner")
private Owner ownerComplex;

}

@XmlRootElement(name = "ownerc")
public class OwnerC {

@XmlElement
int id;

@XmlElement
String fname;

@XmlElement
String lname;
}

要映射的 XML:

<response>
<name>Foo</name>
<owner>1234</owner> <!-- in this case it's only a id -->
</response>

<response>
<name>Foo</name>
<owner> <!-- in this case it's the owner class -->
<id>1234</id>
<fname>Jon</fname>
<lname>Doe</lname>
</owner>
</response>

最佳答案

您可以使用 @XmlAnyElement(lax=true) 来处理这个用例。此批注允许您将任何 XML 解码为 Java 对象(DOM Node)。在第二步中,可以将 Node 解码为所需的对象

响应

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "domain")
public class Response {

@XmlElement
private String name;

@XmlAnyElement(lax=true)
private Object owner;

private String ownerSimple;

@XmlTransient
private Owner ownerComplex;

所有者

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "owner")
public class Owner {

@XmlElement
int id;

@XmlElement
String fname;

@XmlElement
String lname;

解码器

//Unmarshaller. Step 1 - Decodes Response and set a DOM Node at Owner
//Important. Owner class must not be present in JAXB context, letting next step to decode the object properly.
//Owner variable at Response class is annotated with @XmlTransient
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) jaxbUnmarshaller.unmarshal(reader);

//Unmarshaller. Step 2. Convert Node to the suitable Object
//Considering both cases, simple-> String complex -> Owner Object.
String ownerSimple = ((Node)response.getOwner()).getFirstChild().getNodeValue();
if (ownerSimple != null){
response.setOwnerSimple(ownerSimple);
} else {
JAXBContext jaxbContextOwner = JAXBContext.newInstance(Owner.class);
Unmarshaller jaxbUnmarshallerOwner = jaxbContextOwner.createUnmarshaller();
Owner ownerComplex = (Owner) jaxbUnmarshallerOwner.unmarshal((Node)response.getOwner());
response.setOwnerComplex(ownerComplex);
}

//Marshaller to system.out. Your object is well mapped in both cases
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(rx, System.out);

关于java - JAXB 将 1 个 XML 标记映射到 2 个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38377145/

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