开发者

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

开发者 https://www.devze.com 2023-02-20 18:46 出处:网络
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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号