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 ?

1
  • can you show this API call code? Commented Jul 25, 2019 at 16:09

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Have you just copy pasted answer from other SO question instead of commenting this question as a duplicate?
I do not have permissions to mark as duplicate, so yes. If you believe its a duplicate, please mark it as one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.