【发布时间】: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