如何使用JAXB从服务返回的“anyType”创建java对象?
2022-09-01 19:13:37
Web 服务返回由 WSDL 定义的对象:
<s:complexType mixed="true"><s:sequence><s:any/></s:sequence></s:complexType>
当我打印出这个对象的类信息时,它显示为:
class com.sun.org.apache.xerces.internal.dom.ElementNSImpl
但是我需要将此对象解构为以下类的对象:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"info",
"availability",
"rateDetails",
"reservation",
"cancellation",
"error" })
@XmlRootElement(name = "ArnResponse")
public class ArnResponse { }
我知道响应是正确的,因为我知道如何编组此对象的 XML:
Marshaller m = jc.createMarshaller();
m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
m.marshal(rootResponse, System.out);
打印出来:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SubmitRequestDocResponse xmlns:ns2="http://tripauthority.com/hotel">
<ns2:SubmitRequestDocResult>
<!-- below is the object I'm trying to unmarshall -->
<ArnResponse>
<Info />
<Availability>
<!-- etc-->
</Availability>
</ArnResponse>
</ns2:SubmitRequestDocResult>
</ns2:SubmitRequestDocResponse>
如何将我看到的对象转换为我知道它所代表的对象?ElementNSImpl
ArnResponse
此外,我在AppEngine上运行,其中文件访问受到限制。
感谢您的任何帮助
更新:
我已经添加了注释,如下所示:@XmlAnyElement(lax=true)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"content"
})
@XmlSeeAlso(ArnResponse.class)
public static class SubmitRequestDocResult {
@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
但这并没有任何区别。
这是否与内容是一个事实有关?List
以下是我从服务器取回内容后尝试访问内容的代码:
List list = rootResponse.getSubmitRequestDocResult().getContent();
for (Object o : list) {
ArnResponse response = (ArnResponse) o;
System.out.println(response);
}
其输出为:
Jan 31, 2012 10:04:14 AM com.districthp.core.server.ws.alliance.AllianceApi getRates SEVERE: com.sun.org.apache.xerces.internal.dom.ElementNSImpl 不能 cast to com.districthp.core.server.ws.alliance.response.ArnResponse
答:
axtavt的答案做到了。这奏效了:
Object content = ((List)result.getContent()).get(0);
JAXBContext context = JAXBContext.newInstance(ArnResponse.class);
Unmarshaller um = context.createUnmarshaller();
ArnResponse response = (ArnResponse)um.unmarshal((Node)content);
System.out.println("response: " + response);