0

I am using jaxb marshal to convert java object to xml. My convert method looks like this:

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();
}

The problem here is when i print it in logs, the return is coming in proper format. for example:

<?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>

but when i return it to be displayed on screen(in browser) from my controller, it shows like this:

"<?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"

why is it changing the format? what do i need to do to keep the format maintained to display it on screen the same way as its in my logs?

Aleksandr Erokhin
  • 1,904
  • 3
  • 17
  • 32
user9517536248
  • 355
  • 5
  • 24
  • it is not clear from the question how does string representation of xml get displayed in a browser – Aleksandr Erokhin Aug 27 '15 at 17:37
  • @AlexErohin: i am returning the same string back to browser. I want to see it in the same format like its getting displayed in logs but somehow its getting changed totally – user9517536248 Aug 27 '15 at 17:41
  • How does this string get displayed in a browser? Is it written out by a servlet as a response or is it displayed as a part of html page? What html component is responsible for displaying it? ( It might also be responsible for escaping string characters.) – Aleksandr Erokhin Aug 27 '15 at 18:14
  • @AlexErohin: i'm returning it as `ResponseEntity(marshallerEx(tickets), HttpStatus.OK);` – user9517536248 Aug 27 '15 at 18:23

1 Answers1

0

I suggest you to manually set content-type of RestController response either to application/xml (if you want browser to render xml tree) or to text/plain (if you want it to display plain text only). This would force the expected representation.

HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("content-type", "text/plain");
return new ResponseEntity<String>(marshallerEx(tickets), responseHeaders, HttpStatus.OK);

Also, seems like a similar problem is described in this thread.

Community
  • 1
  • 1
Aleksandr Erokhin
  • 1,904
  • 3
  • 17
  • 32