问题
I have below XML which I am getting from third party(rest service)
<response>
<error>Document Too Small</error>
<error>Barcode Not Detected</error>
<error>Face Image Not Detected</error>
</response>
I am calling third party service with below code which is trying to convert the xml to respective java object -
restTemplate.postForObject("/test", new HttpEntity<>(request, headers), Eror.class);
We have added the MappingJackson2XmlHttpMessageConverter-
MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter();
converter.getObjectMapper().registerModule(new JaxbAnnotationModule());
Below is the Eror.class code -
@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;
}
}
The same code works fine if we have simple types like string, int but issue comes when we have list of string. I get the following exception -
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
FYI if I did manual parsing from xml to respective java using jaxb marshaller like below then it worked properly -
JAXBContext jaxbContext = JAXBContext.newInstance(Eror.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Eror err = (Eror) jaxbUnmarshaller.unmarshal(new File("c:/error.xml"));
Any sort of help is much appreciated.
回答1:
It is always better to use Jaxb for xml for marshalling and unmarshalling. Still if you want to use, jackson way of doing. You have to do in the following manner.
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();
}
For better understanding its usage, refer below the links. 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
来源:https://stackoverflow.com/questions/56276338/autmapping-of-xml-list-of-string-response-by-rest-service-to-respective-java-obj