有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Apache CXF客户端解组响应

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

下面是我调用rest端点的实现。我使用的是ApacheCXF2.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) 个答案

  1. # 1 楼答案

    我的解决方案

    我在一台Tomee服务器上运行这个项目。 在Tomee lib文件夹中,项目提供了一个抛弃库

    servers/apache-tomee-1.7.1-jaxrs/lib/jettison-1.3.4.jar

    可以使用抛弃库中的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;
        }
    }