我收到了一条响应消息的 xsd,我正在尝试将 xml 响应解析为 jaxb 生成的类。我首先遇到了一个问题,即根 xml 元素被称为“response”,但还有一个名为“response”的嵌套类,因此出现编译错误。为了解决这个问题,我发现在 xsd 中我可以使用 jaxb:class 注释来更改嵌套类的名称,该类创建如下,嵌套类现在生成为“callReport7Response”而不是“response”。
<xs:element name="callReport7" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="request">
<xs:annotation><xs:appinfo><jaxb:class name="callReport7Request"/></xs:appinfo></xs:annotation>
<xs:complexType>
<xs:complexContent>
<xs:extension base="xs:anyType">
<xs:attribute name="time" type="xs:string"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:element>
<xs:element name="response">
<xs:annotation><xs:appinfo><jaxb:class name="callReport7Response"/></xs:appinfo></xs:annotation>
<xs:complexType>
<xs:complexContent>
<xs:extension base="xs:anyType">
<xs:attribute name="time" type="xs:string"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
不幸的是,当我尝试解组响应时,我收到错误消息说它无法将“callReport7Response”解析为“响应”
java看起来像这样:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"any"})
@XmlRootElement(name = "response")
public static class CallReport7Response {
@XmlAnyElement
protected List<Element> any;
@XmlAttribute
protected String time;
似乎这就是它试图将我的嵌套对象转换为顶级对象。
09:28:34,608 ERROR [STDERR] java.lang.ClassCastException: uk.co.test.dashboard.dal.Response$Insurer$Subject$CallReport7$CallReport7Response cannot be cast to uk.co.test.dashboard.dal.Response
我正在使用此代码解组:
Response response = new Response();
StringReader reader = new StringReader(resp);
try {
JAXBContext context = JAXBContext.newInstance(response.getClass());
Unmarshaller unmarshaller = context.createUnmarshaller();
Object o = unmarshaller.unmarshal(reader);
response = (Response) o;
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}