spring_hiber
spring_hiber

Reputation: 135

How to iterate json and save to list?

I have a situation in which my json array has more than one key within an array like this...

"information"{
     "info": [
   {
    "name": "Susan",
    "address": "101 Blue Street",
    },
    
   {
    "name": "John",
    "address": "203 Red Street",
  }
 ]
 }
 

I have no problem getting both names if I do this...

     String firstName = firstObject.getJSONArray("info").optJSONObject(0).optString("name");
     String secondName = firstObject.getJSONArray("info").optJSONObject(1).optString("name");
     

However, there is no guarantee that only two objects will be returned so I am now attempting to loop through these items and saving to arraylist for further processing.

Below is what I have so far. I'm getting the names (nameString) but they are not saving to the list. The list clears on next iteration.

What am I doing wrong?

     JSONObject firstObject = response.optJSONObject("information");
     JSONArray infoArray = firstObject.getJSONArray("info");

     String nameString;
     String save;
     List<String> al = new ArrayList<String>();
     List<String> al2 = new ArrayList<>();


     for(int index = 0; index < infoArray.length(); index++) {
         JSONObject jsonObject = infoArray.getJSONObject(index);
         nameString = jsonObject.getString("name");
         System.out.println("name: " + nameString);
         
         
         al = Arrays.asList(nameString);
         
         for(String s: al){
            
           log.info("nameString  " + s);
          
          save = s;
         al2.add(save);

Upvotes: 1

Views: 1522

Answers (2)

Praseeth S
Praseeth S

Reputation: 121

You have already got the name in the line nameString = jsonObject.getString("name") There is no need to use the second for loop. Just add the nameString object into the list. al.add(nameString) will save the name in to the list.

Upvotes: 1

Ezra
Ezra

Reputation: 539

In each iteration your are creating a new ArrayList from the nameString. You should simply add to the existing list instead:

al.add(nameString);

Upvotes: 1

Related Questions