我正在尝试使用一个类映射我从XML请求获得的响应。 但xml响应有所不同,具体取决于某些设置。例如,在响应中,我得到标签“owner”,其中填充了所有者对象的ID。如果我在我的请求中添加一个设置,我将返回完整的所有者数据,如firstname和lastname。现在我想将owner标记映射到String变量或Class,具体取决于响应。
示例:
@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>
答案 0 :(得分:1)
您可以使用@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 强>
//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);