2015-11-17 135 views
1

如何使用Apache CXF休息客戶端將JSON響應字符串解組爲正確的對象?Apache CXF客戶端解組響應

下面是我的實現,它調用其餘的終點。我正在使用Apache CXF 2.6.14

請注意,響應狀態會告訴我要解組到哪個對象。

public Object redeem(String client, String token) throws IOException { 
    WebClient webClient = getWebClient(); 
    webClient.path(redeemPath, client); 

    Response response = webClient.post(token); 
    InputStream stream = (InputStream) response.getEntity(); 

    //unmarshal the value 
    String value = IOUtils.toString(stream); 

    if (response.getStatus() != 200) { 
     //unmarshall into Error object and return 
    } else { 
     //unmarshall into Token object and return 
    } 
} 

回答

0

我的解決方案。

我在Tomee服務器上運行項目。 在Tomee lib文件夾中,該項目提供了一個拋棄庫。

服務器/阿帕奇-tomee-1.7.1-JAXRS/LIB /拋放-1.3.4.jar

人們可以利用JSONObject這是拋放LIB內部結合JAXBContext來解析JSON字符串被髮回。

public Object redeem(String client, String token) throws Exception { 
    WebClient webClient = getWebClient(); 
    webClient.path(redeemPath, client); 

    Response response = webClient.post(token); 
    InputStream stream = (InputStream) response.getEntity(); 

    //unmarshal the value 
    String value = IOUtils.toString(stream); 

    //use the json object from the jettison lib which is located in the Tomee lib folder. 
    JSONObject jsonObject = new JSONObject(value); 

    if (response.getStatus() != 200) { 

     JAXBContext jc = JAXBContext.newInstance(ResourceError.class); 
     XMLStreamReader reader = new MappedXMLStreamReader(jsonObject); 
     Unmarshaller unmarshaller = jc.createUnmarshaller(); 

     ResourceError resourceError = (ResourceError) unmarshaller.unmarshal(reader); 
     return resourceError; 

    } else { 

     JAXBContext jc = JAXBContext.newInstance(Token.class); 
     XMLStreamReader reader = new MappedXMLStreamReader(jsonObject); 
     Unmarshaller unmarshaller = jc.createUnmarshaller(); 

     Token token = (Token) unmarshaller.unmarshal(reader); 
     return token; 
    } 
}