【问题标题】:How can I return XML from a Apache CXF REST service and have it converted to json?如何从 Apache CXF REST 服务返回 XML 并将其转换为 json?
【发布时间】:2011-03-31 08:43:39
【问题描述】:

我有一个使用 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。

【问题讨论】:

  • 我可以从代码中看到 JSONProvider 将与 JAXBElement 一起使用,并通过返回一个虚拟 JAXBElement 来验证这一点。那么如何将我的 XML 文本转换为 JAXBElement 的树呢?还是有其他方法?

标签: java json web-services cxf jax-rs


【解决方案1】:

最后我采取了不同的(更好的)方法。 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2010-12-18
    相关资源
    最近更新 更多