So I have this controller. I am appending an xml string inside the response which is also xml.
@GetMapping(value = "/testxml", consumes = { MediaType.APPLICATION_XML_VALUE },
produces = { MediaType.APPLICATION_XML_VALUE })
public ResponseData getXml(@RequestBody RequestData rData) {
String xml = "<TEST><INNER_TEST>test</INNER_TEST></TEST>";
ResponseData response = new ResponseData();
response.setAge(rData.getAge());
response.setXml(xml);
response.setName(rData.getName());
return response;
}
I am expecting this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<responseData>
<age>17</age>
<name>sample</name>
<xml><TEST><INNER_TEST>test</INNER_TEST></TEST></xml>
</responseData>
but instead got this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<responseData>
<age>17</age>
<name>sample</name>
<xml><TEST><INNER_TEST>test</INNER_TEST></TEST></xml>
</responseData>
now, I know that < and > (plus others) gets converted to that escaped character when spring boot marshalls the response, but is there a way to ignore that given:
-xml can be any form of xml. No format. Could be QWERTY or 12345 or anything as long as it's xml. -cannot use CDATA. Must keep the parent response's format of whatever xml string
Answer:
Use this on your configuration class (@Configuration) to override xml marshalling so it does not escape the characters.
@Bean
public HttpMessageConverter<Object> messageConverter() {
return new MarshallingHttpMessageConverter(getJaxb2Marshaller());
}
@Bean
public Jaxb2Marshaller getJaxb2Marshaller() {
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
Map<String, Object> map = new HashMap<String, Object>();
jaxb2Marshaller.setClassesToBeBound(TestModel.class);
map.put(CharacterEscapeHandler.class.getName(),
new CharacterEscapeHandler() {
@Override
public void escape(char[] ac, int i, int j, boolean flag,
Writer writer) throws IOException {
writer.write(ac, i, j);
}
});
jaxb2Marshaller.setMarshallerProperties(map);
return jaxb2Marshaller;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.