Apache CXF客户端解组响应

时间:2015-11-17 09:14:47

标签: java json apache cxf

如何使用Apache CXF rest客户端将JSON响应字符串解组为正确的对象?

以下是我的实现,它调用了其余的终点。我正在使用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
    }
}

1 个答案:

答案 0 :(得分:0)

我的解决方案。

我在Tomee服务器上运行该项目。 在Tomee lib文件夹中,项目提供了一个jettison lib。

  

服务器/阿帕奇-tomee-1.7.1-JAXRS / LIB /抛放-1.3.4.jar

可以使用jettison lib中的JSONObject与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;
    }
}