2011-03-31 53 views
0

我有一個使用Apache CXF和Spring構建的簡單REST服務。我正在使用擴展映射的東西來返回json或xml取決於URL(http://.../hello.json等)。當JAXB註釋的Java類返回時,這非常有效。如何從Apache CXF REST服務返回XML並將其轉換爲json?

是否有一種簡單的方法讓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。

+0

我可以從代碼的JSONProvider將與JAXBElement的工作,並返回一個空的JAXBElement證實看到。那麼如何將我的XML文本轉換爲JAXBElement的樹?還是有另一種方法? – 2011-03-31 10:24:04

回答

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(); 
} 
相關問題