[英]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.