REST服务使用RestTemplate.postForObject(.....)将字符串响应的XML列表自动映射到相应的Java对象

时间:2019-05-23 13:27:13

标签: jackson jaxb resttemplate spring-restcontroller jackson-databind

我下面有从第三方(休息服务)获得的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"));

非常感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:0)

最好使用Jaxb for xml进行编组和解组。仍然,如果您想使用,杰克逊的做法。您必须按照以下方式进行操作。

XmlMapper mapper = new XmlMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper);
String xmlString = "your xml response";

try {
     Eror eror = mapper.readValue(xmlString, Eror.class);
     System.out.println("eror = " + eror);
  } catch (IOException e) {
      e.printStackTrace();
  }

为更好地了解其用法,请参阅下面的链接。 http://websystique.com/springmvc/spring-mvc-requestbody-responsebody-example/

https://www.concretepage.com/spring-4/spring-4-rest-xml-response-example-with-jackson-2

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverter.html