1

I am using openjdk 11 and I am calling an api that is returning content type json. I parsing the response and converting into a string like this ( Need to do it this way as I am expecting responses in different formats/structure):

    HttpEntity entity = response.getEntity();

    try
    {
        responseBody = EntityUtils.toString( entity );
    }
    catch ( Exception e )
    {
        LOG.error( "Unable to parse response", e );
        e.printStackTrace();
    }

Where response is a org.apache.http.HttpResponse type object.

After converting into a string, the response looks like :

["abc","bcd","cde"]

Now, I was trying to put this into jsonObject or JsonArray as

 JSONArray jsonArray = new JSONArray(responseBody);
 Arrays.asList(jsonArray).stream().forEach(e-> LOG.info("Connector: " + e));

While my jsonArray looks good, getting error like :

["abc","bcd","cde"] is not an array

Question is : How to convert that jsonArray into a List in Java ?

azurefrog
  • 10,785
  • 7
  • 42
  • 56
VictorGram
  • 2,521
  • 7
  • 48
  • 82

1 Answers1

2

I assume JSONArray comes from Android. You can just do this:

ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
    int len = jsonArray.length();
    for (int i=0;i<len;i++){
        list.add(jsonArray.get(i).toString());
    }
}

Source: Convert Json Array to normal Java list

Alan Sereb
  • 2,358
  • 2
  • 17
  • 31