0

Well, I want to parse JSON code to my custom ArrayList which has title and description parameters.

[
   {
        "title" : "title1",
        "description" : "desc1"
    },
    {  
        "title" : "title2",
        "description" : "desc2"
    }
 ]

Here is my code:

ArrayList<Model> arr = new ArrayList<>();

    JSONArray ja = new JSONArray(new JSONObject(jsonString).getJSONArray(jsonString);

for(int i = 0; i < ja.length(); i++)
{
     JSONObject jo = ja.getJSONObject(i);

String title = jo.getString("title");
String desc = jo.getString("description");

arr.add(new Model(title, desc));
}

but instead of getting the whole list, I get only first element... parsed values look like:

Title:  title1
Desc: desc1

So, I cant read the whole array, help me.

pa1.Shetty
  • 401
  • 3
  • 16

3 Answers3

2

Try this, You might have a problem when you are using the JSON array line

                JSONArray jsonArray = new JSONArray(response);

                ArrayList<Model> arr = new ArrayList<>();
                for (int i = 0; i < jsonArray.length(); i++) {

           String title = 
                  jsonArray.getJSONObject(i).getString("title");
                 String description= 
                 jsonArray.getJSONObject(i).getString("description");

                 arr.add(new Model(title, description));
               }

This should work. Let me know after you implement this.

Brahma Datta
  • 1,102
  • 1
  • 12
  • 20
2

Feed the JSONArray constructor the JSON string of objects

Change

    JSONArray ja = new JSONArray(new 
    JSONObject(jsonString).getJSONArray(jsonString);

To

    JSONArray ja = new JSONArray(jsonString);
Joshua Gainey
  • 311
  • 3
  • 4
0

I am getting issue with parsing your string with

JSONArray ja = new JSONArray(new JSONObject(jStrArr).getJSONArray(jStrArr));

So, I just tried your json string in my project and did some minor changes in the code. It's working fine now. I have added your json string in static variable for test as below.

String jStrArr = "[{\"title\" : \"title1\", \"description\" : \"desc1\" }, { \"title\" : \"title2\", \"description\" : \"desc2\" }]";

ArrayList<Model> listModel = new ArrayList<>();

try {

    JSONArray jArr = new JSONArray(jStrArr);

    for (int i = 0; i < jArr.length(); i++) {

        JSONObject jObj = new JSONObject(jArr.getString(i));

        String title = jObj.getString("title");
        String desc = jObj.getString("description");

        listModel.add(new Model(title, desc));
    }
} catch (Exception e) {
    e.printStackTrace();
}

So now while i debug the code, i got both json data in Array List. Please check below output.

enter image description here

Note: I have prepared this code based on your json string only. If you have a Json Object as a parent of this Json Array then there might be minor changes.

Ajay Mehta
  • 843
  • 5
  • 14