我收到了一个响应消息的xsd,正在尝试将xml响应解析成jaxb生成的类。一开始我遇到了一个问题,根元素被称为"response",但也有一个嵌套类名为"response",这导致编译错误。为了解决这个问题,我发现在xsd中可以使用jaxb:class注释来更改创建的嵌套java类的名称。下面是嵌套类现在生成为“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" 解析为 "response"。
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();
}