我想創建模型類下面的xml:JAXB解組使用Groovy
<Response>
<Success>N</Success>
<Errors>
<Error>
<Number>29002</Number>
<Message>A key field was missing from the control xml</Message>
</Error>
<Error>
<Number>29004</Number>
<Message>Unable to accept messages at this time</Message>
</Error>
</Errors>
</Response>
這是我Response.class
@XmlRootElement (name="Response")
@XmlAccessorType(XmlAccessType.FIELD)
class Response {
@XmlElement(name="Success")
private String success
@XmlElement(name="Errors")
private Errors errors
public String getSuccess() {
return success
}
public Errors getErrors() {
return errors;
}
}
這是我Errors.class
@XmlRootElement(name="Errors")
@XmlAccessorType(XmlAccessType.FIELD)
class Errors {
public Errors() {
errorList = new ArrayList<Error>()
}
@XmlElement(name = "Errors")
private List<Error> errorList;
public List<Error> getErrorList() {
return errorList
}
}
這是我的Error.class
@XmlRootElement(name="Error")
@XmlAccessorType(XmlAccessType.FIELD)
class Error {
@XmlElement(name="Number")
private int number
@XmlElement(name="Message")
private String message
public int getNumber() {
return number
}
public String getMessage() {
return message
}
}
下面是我的解組類UnmarshallResponse.class
try {
//XML and Java binding
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class)
//class responsible for the process of de-serializing
//XML data into Java object
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Source source = new StreamSource(new java.io.StringReader(myXml))
//log.info("source: "+myXml.toString())
Response response = (Response) jaxbUnmarshaller.unmarshal(source)
//print the response for debugging
log.info("Success: " + response.getSuccess())
Errors errors = response.getErrors()
List<Error> errorList = errors.getErrorList()
log.info("Size of Error List: " + errorList.size())
errorList.each {
Error element
log.info("errorNumber: " + element.getNumber())
log.info("errorMessage: " + element.getMessage())
}
log.info("End of XML.")
}catch (JAXBException e) {
log.error("JAXBException: "+e.getMessage())
}
我能夠獲得成功的價值,但錯誤列表不來了,它顯示錯誤列表大小爲0的輸出如下到來:
成功:N 錯誤列表的大小:0
任何人可以幫助我瞭解,我很想念在哪裏?
感謝
感謝您的快速回復。它解決了這個問題。 – Anzar 2014-10-22 06:27:51