簡體   English   中英

如何從Apache CXF REST服務返回XML並將其轉換為json?

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

我有一個使用Apache CXF和Spring構建的簡單REST服務。 我正在使用擴展映射的東西來根據URL(http://.../hello.json等)返回json或xml。 當返回帶有JAXB注釋的Java類時,此方法效果很好。

有沒有一種簡單的方法可以使Apache CXF將手工制作的XML自動轉換為json? 我需要從服務中退貨嗎?

我知道我可以如下返回XML,但這不會自動將XML轉換為json:

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

我將從文件系統或其他一些存儲中返回靜態XML文檔。 我需要能夠返回json。

最后,我采取了另一種(更好)的方法。 XML文檔由Servlet提供,並通過以下代碼轉換為json:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM