【问题标题】:Can't unmarshall XML from exception response body无法从异常响应正文中解组 XML
【发布时间】:2020-04-17 18:17:50
【问题描述】:

当试图解组 XML 错误响应时,对象中的所有元素都为空。 使用 @XmlAnyElement(lax = true) unmarshaller 可以找到所有标签,但它们仍然为空。 这发生在使用 RestTemplate 的 catch 块上。当响应为 200 时,使用相同的方法来解组响应正文。

xml 文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<problem xmlns="urn:ietf:rfc:7807">
    <type>https://foo.bar</type>
    <title>Foo</title>
    <status>400</status>
    <detail>FooBar</detail>
</problem>

我的班级:

import java.util.List;

import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement(name = "problem", namespace = "urn:ietf:rfc:7807")
public class ErroDict {

    @XmlElement(name = "type")
    private String type;

    @XmlElement(name = "title")
    private String title;

    @XmlElement(name = "status")
    private String status;

    @XmlAnyElement(lax = true)
    private List<String> tags;
}

代码:

HttpStatus status = null
...try block...
catch (final HttpClientErrorException e) {
status = e.getStatusCode();
if(status != null && status == HttpStatus.BAD_REQUEST) {
  jaxbContext = JAXBContext.newInstance(ErroDict.class);
  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  ErroDict erro = (ErroDict) jaxbUnmarshaller.unmarshal(new StringReader(e.getResponseBodyAsString()));

这让我在所有元素上都为 null,并且 List 还包含所有三个具有 null 值的元素

【问题讨论】:

    标签: java xml jaxb unmarshalling


    【解决方案1】:

    我找到的一个临时解决方案是: 将类 ErrorDict 放在一个包中。 在包中我创建了 package-info.java 类并放入

    @XmlSchema (namespace = "urn: ietf: rfc: 7807", elementFormDefault = XmlNsForm.QUALIFIED)

    从 ErroDict 类中移除命名空间!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多