在解组XML响应并将其绑定到POJO时遇到问题。最后只有null值的对象,这也意味着对象类没有定义正确结束。
SOAP XML String
String xmlToParse = "<?xml version="1.0" encoding="UTF-8"?><soap:env:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:soap.origin.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><eventResponse><result><field1>data1</field1><boolean1>false</boolean1><userId>123abc</userId><userinfo><boolean2>true</boolean2><field2>data2</field2><orgId>123abc</orgId><userCode xsi:nil="true"/></userinfo></result></eventResponse></soapenv:Body></soapenv:Envelope>"
ParseXML.java
private EventResponse parseXmlResult(String xmlToParse){
JAXBContext jaxbContext = JAXBContext.newInstance(EventResponse.class)
SOAPMessage msg = MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(xmlToParse.getBytes()));
Unmarshaller um = jaxbContext.createUnmarshaller();
EventResponse response = (EventResponse) um.unmarshall(message.getSOAPBody().extractAsDocument());
return response;
}
EventResponse类:
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name=eventResponse", namespace="urn:soap.origin.com")
public class EventResponse{
@XmlElement(name=LoginResult")
private Result result;
}
结果类:
@Getter
@Setter
@JsonJsonInclude.Include.NON_NULL)
@XmlAccessorType(XmlAccessType.FIELD)
public class Result{
@XmlElement(name="field1", nillable="true")
private String field1;
@XmlElement(name="boolean2")
private Boolean boolean2;
@XmlElement(name="userId", nillable="true")
private String userId;
@XmlElement(name="GetUserInfo")
private UserInfo userInfo;
}
用户信息类:
@Getter
@Setter
@JsonJsonInclude.Include.NON_NULL)
@XmlAccessorType(XmlAccessType.FIELD)
public class UserInfo{
@XmlElement(name="boolean2")
private Boolean boolean2;
@XmlElement(name="field2", nillable="true")
private String field2;
@XmlElement(name="orgId")
private String orgId;
@XmlElement(name="userCode", nillable=true)
private String userCode;
}
XML定义,如果有帮助的话:
<element name="eventResponse">
<complexType>
<sequence>
<element name="result" type="tns:EventResult">
</sequence>
</complexType>
</element>
<complexType name "EventResult">
<sequence>
<element name="field1" type="xsd:string" nillable="true"/>
<element name="boolean1" type="xsd:boolean" />
<element name="userId" type="tns:ID" nillable="true"/>
<element name="userInfo" type="tns:GetUserInfo" minOccurs="0"/>
</sequence>
</complexType>
<complexType name "GetUserInfo">
<sequence>
<element name="boolean2" type="xsd:boolean" />
<element name="field2" type="xsd:string" nillable="true"/>
<element name="orgId" type="tns:ID"/>
<element name="userCode" type="tns:string" nillable="true"/>
</sequence>
</complexType>
我通过在xml标记和tns值之间切换来尝试@XmlElement注释的命名,但无济于事。
我能够找出问题是什么。首先,我需要创建一个GetUserInfo
类,所以我重构了现有的UserInfo
类。之后,我需要将根元素中使用的名称空间添加到模式中声明的所有元素中。