繁体   English   中英

Apache CXF客户端解组响应

[英]Apache CXF client unmarshal response

如何使用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
    }
}

我的解决方案。

我正在Tomee服务器中运行该项目。 在Tomee lib文件夹中,该项目提供了一个抛弃的lib。

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

可以将JSONObject库中的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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM