Itsik Mauyhas
Itsik Mauyhas

Reputation: 4002

split json object from json array in java

I am sending API call to a service that return a json array like this :

[Object, Object ....]

via my java http request. the resulat are stored in a string:

StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

I need to find a way to split this string to by json objects so each new string will contain only one object. Thanks.

Upvotes: 3

Views: 12558

Answers (1)

ThomasThiebaud
ThomasThiebaud

Reputation: 11999

Instead of using the split function, you can convert your String to a JSONArray and then iterate throw the array

JSONArray jsonArray = new JSONArray(response.toString());
for(int i=0; i<jsonArray.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    String jsonObjectAsString = jsonObject.toString();
}

Upvotes: 10

Related Questions