【发布时间】:2019-05-23 13:27:12
【问题描述】:
我有以下从第三方获取的 XML(休息服务)
<response>
<error>Document Too Small</error>
<error>Barcode Not Detected</error>
<error>Face Image Not Detected</error>
</response>
我正在使用以下代码调用第三方服务,该代码试图将 xml 转换为相应的 java 对象 -
restTemplate.postForObject("/test", new HttpEntity<>(request, headers), Eror.class);
我们添加了 MappingJackson2XmlHttpMessageConverter-
MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter();
converter.getObjectMapper().registerModule(new JaxbAnnotationModule());
下面是 Eror.class 代码 -
@XmlRootElement(name = "response")
public class Eror {
private List<String> error;
public List<String> getError() {
return error;
}
public void setError(List<String> error) {
this.error = error;
}
}
如果我们有像字符串、整数这样的简单类型,同样的代码可以正常工作,但是当我们有字符串列表时就会出现问题。 我得到以下异常 -
Exception cause -
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of VALUE_STRING token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of VALUE_STRING token
仅供参考,如果我使用 jaxb marshaller 手动从 xml 解析到相应的 java,那么它可以正常工作 -
JAXBContext jaxbContext = JAXBContext.newInstance(Eror.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Eror err = (Eror) jaxbUnmarshaller.unmarshal(new File("c:/error.xml"));
非常感谢任何形式的帮助。
【问题讨论】:
-
我还是无法理解问题,一旦我得到,我会帮助你。你能告诉我确切的问题吗,因为我看到你已经写了 jaxb unmarshaller。
-
jaxb unmarshaller 是我可以将 xml 转换为 java 对象的一种方法。当我们处理休息服务时,resttemplate 提供了自动完成这项工作的工具。在这里,我无法将 xml 元素列表转换为相应的 java 对象。我希望它会有所帮助。
-
我明白了,你想让 MappingJackson2XmlHttpMessageConverter 自动转换对象吗?
-
是的。这就是我想要的
-
好的,我帮你解决。
标签: jackson jaxb resttemplate spring-restcontroller jackson-databind