0

I'm using jersey to call different Rest Api and I've searched for a solution to convert the response to java array or list this is the output :

[{"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}]

I tried resp.getEntity(String.class) but this returned a string and i need to convert it to List or Array or any other data structure so i can manipulate the data because i'm trying to make charts.

this the method that i used to make the API Call:

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;
}
  • 1
    Possible duplicate of [How to use Jackson to deserialise an array of objects](https://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects) – Arnaud Oct 15 '18 at 09:14
  • Use `getEntity(YourType[].class)` or `getEntity(new GenericType>(){})`. You need to make sure you have a JSON provider in your app. – Paul Samsotha Oct 17 '18 at 06:47

2 Answers2

0

It can be achieved by following snippet:

 String response = response.getEntity().toString();
 JSONArray jsonArray = (JSONArray) new JSONParser().parse(response);
 String[] stringArray = jsonArray.toArray(new String[jsonArray.size()]);
Vithursa Mahendrarajah
  • 1,194
  • 2
  • 15
  • 28
0

I solved it i used the objectMapper from jackson

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