如何将ClientResponse转换为Java数组或Java对象?

时间:2018-10-15 09:11:44

标签: java json api jersey response

我正在使用jersey来调用其他的Rest Api,并且我正在寻找一种将响应转换为Java数组的解决方案,或者将其输出为列表:

[{"name":"TEST","number":22,"successNumber":11,"runnedNumber":20,"percentage":0.5},{"name":"SCENARIO","number":29,"successNumber":10,"runnedNumber":12,"percentage":0.34},{"name":"TESTCASE","number":11,"successNumber":6,"runnedNumber":9,"percentage":0.55}]

我尝试了resp.getEntity(String.class),但这返回了一个字符串,我需要 将其转换为List或Array或任何其他数据结构,以便我可以操纵数据,因为我正在尝试制作图表。

这是我用来进行API调用的方法:

public ClientResponse callApi(String url) throws IOException {

    String name = "admin";
    String password = "admin";
    String authString = name + ":" + password;
    String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
    System.out.println("Base64 encoded auth string: " + authStringEnc);
    Client restClient = Client.create();
    WebResource webResource = restClient.resource(url);
    ClientResponse resp = webResource.accept("application/json")
            .header("Authorization", "Basic " + authStringEnc)
            .get(ClientResponse.class);
    if(resp.getStatus() != 200){
        System.err.println("Unable to connect to the server");
    }
    String output = resp.getEntity(String.class);
    System.out.println("response: "+output);
    return resp;
}

2 个答案:

答案 0 :(得分:0)

可以通过以下代码段实现:

 String response = response.getEntity().toString();
 JSONArray jsonArray = (JSONArray) new JSONParser().parse(response);
 String[] stringArray = jsonArray.toArray(new String[jsonArray.size()]);

答案 1 :(得分:0)

我解决了它,我使用了杰克逊的objectMapper

    String json = "json string";
    ObjectMapper objectMapper = new ObjectMapper();
    List<YourClass> listClass = objectMapper.readValue(json, new TypeReference<List<YourClass>>(){});