簡體   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