我使用jaxb marshal将java对象转换为xml。我的转换方法如下所示:
protected String marshallerEx(Tickets tickets) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Tickets.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
// Marshal the tickets list in console
jaxbMarshaller.marshal(tickets, sw);
LOGGER.info("marshal -> " + sw.toString());
return sw.toString();
}
这里的问题是当我在日志中打印时,返回的格式正确。例如:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tickets>
<ticket>
<assignedQueueId>61</assignedQueueId>
<category>11</category>
<cause>0</cause>
<createDate>2015-08-19T13:34:18-04:00</createDate>
<customFields/>
</ticket>
</tickets>
但当我将其返回以从我的控制器显示在屏幕上(在浏览器中)时,它显示如下:
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<tickets>\n <ticket>\n <assignedQueueId>61</assignedQueueId>\n <category>11</category>\n <cause>0</cause>\n <createDate>2015-08-19T13:34:18-04:00</createDate>\n <customFields/>\n </ticket>\n</tickets>\n"
为什么要改变格式?我需要做些什么来保持格式保持在屏幕上以与我的日志相同的方式显示它?
答案 0 :(得分:0)
我建议您手动将RestController响应的content-type
设置为application/xml
(如果您希望浏览器呈现xml树)或text/plain
(如果您希望它显示纯文本)只要)。这将迫使预期的代表性。
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("content-type", "text/plain");
return new ResponseEntity<String>(marshallerEx(tickets), responseHeaders, HttpStatus.OK);
此外,似乎在此thread中描述了类似的问题。