【问题标题】:How to convert a ClientResponse to a java array or java object?如何将 ClientResponse 转换为 java 数组或 java 对象?
【发布时间】:2018-10-15 09:11:44
【问题描述】:

我正在使用 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;
}

【问题讨论】:

标签: java json api jersey response


【解决方案1】:

可以通过如下sn-p来实现:

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

【讨论】:

  • 我应该使用哪个依赖?
  • org.json.simple.JSONArray, org.json.simple.JSONObject
【解决方案2】:

我解决了,我使用了 jackson 的 objectMapper

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多