简体   繁体   中英

How can I return XML from a Apache CXF REST service and have it converted to json?

I have a simple REST service built using Apache CXF and Spring. I am making use of the extension mapping stuff to return json or xml depending on the URL (http://.../hello.json etc.). This works very well when JAXB annotated Java classes are returned.

Is there an easy way to get Apache CXF to convert hand crafted XML to json automatically? What would I need to return from my service?

I know I can return the XML as follows but this won't auto convert the XML to json:

public Response get() {
    return Response.status(200).type(MediaType.TEXT_XML).entity("<hello>world</hello>").build();
}

I will be returning static XML documents from the file system or some other store. I need to be able to return json instead.

I took a different (better) approach in the end. The XML docs are served by a servlet and converted to json with this code:

public void convertXmlToJson(InputStream in, OutputStream out) throws XMLStreamException {
    XMLEventReader xmlIn = XMLInputFactory.newFactory().createXMLEventReader(in);
    OutputStreamWriter osw;
    try {
        osw = new OutputStreamWriter(out, "UTF8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.toString(), e); // not possible really
    }
    MappedXMLStreamWriter jsonOut = new MappedXMLStreamWriter(new MappedNamespaceConvention(), osw);
    AbstractXMLEventWriter xmlOut = new AbstractXMLEventWriter(jsonOut);
    while (xmlIn.hasNext()) {
        XMLEvent ev = xmlIn.nextEvent();
        if (ev instanceof Characters && ((Characters)ev).isWhiteSpace()) {
            continue;
        }
        xmlOut.add(ev);
    }
    xmlOut.close();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM