使用 Groovy 解组 JAXB

Anz*_*zar 2 xml groovy jaxb unmarshalling

我正在尝试为以下 xml 创建模型类:

<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>
Run Code Online (Sandbox Code Playgroud)

这是我的 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 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
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 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
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是我的解组类 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())
}
Run Code Online (Sandbox Code Playgroud)

我能够获取成功的值,但错误列表没有出现,它显示错误列表大小为 0。输出如下:

成功:N 错误列表大小:0

有人可以帮助我理解我缺少的地方吗?

谢谢

lex*_*ore 5

您已将Error元素命名为Errors(注意s最后的)。请参阅Errors.errorList. 因此 JAXB 不会处理您的Error元素。

顺便说一句,您不一定需要该Errors课程。你可以用@XmlElementWrapper(name="Errors")它代替。