2015-11-17 138 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; 
    } 
}