java - 如何使用 JAXB 从服务返回的 'anyType' 创建 java 对象?

标签 java serialization jaxb unmarshalling

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 cannot be 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);

最佳答案

您可以将该对象传递给 Unmarshaller.unmarshal(Node),它应该能够解码它。

关于java - 如何使用 JAXB 从服务返回的 'anyType' 创建 java 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9080259/

相关文章:

java - Protocol Buffer 比序列化更好?

java - Hibernate @Any 无法获取对象

java - 待遇到类内场。通过 getter 还是显式?

java - 使用 Jackson 解析 json 中的 boolean 值时的额外数据

Java 的序列化对象表示

java - 想要在 jaxb2-maven-plugin 生成的类中使用 @XmlRootElement

java - XJC - 忽略 nillable=true

Java:使用 JAXB 解析 xml 文件后生成 SQL 并插入数据库而不重复的最佳方法?

java - 静态方法总是同时返回

java - 重新打开应用程序时恢复计时器