java – How to get and store it to variable the arrays inside arrays in Android?-ThrowExceptions

Exception or error:

I am trying to store in my model the response, but how can I get the value if it is inside of another array? the response that I have is kinda confusing for me. this is the look of the response.

{
  "data": [
    {
      "id": "1",
      "directory_name": "Directory 1",
      "details": [
        {
          "sub_directory_name": "Sub Directory 1",
          "address": "sub",
          "email": [
            {
              "key": 0,
              "value": "123"
            }
          ],
          "contact_no": [
            {
              "key": 0,
              "value": "123"
            }
          ],
          "description": ""
        },
        {
          "sub_directory_name": "Sub Directory 2",
          "address": "National",
          "email": [
            {
              "key": 0,
              "value": "123"
            }
          ],
          "contact_no": [
            {
              "key": 0,
              "value": "123"
            }
          ],
          "description": ""
        },
        {
          "sub_directory_name": "Sub Directory 3",
          "address": "Syb",
          "email": [
            {
              "key": 0,
              "value": "123"
            },
            {
              "key": 1,
              "value": "123"
            }
          ],
          "contact_no": [
            {
              "key": 0,
              "value": "123"
            },
            {
              "key": 1,
              "value": "123"
            }
          ],
          "description": ""
        },
        {
          "sub_directory_name": "Sub Directory 4",
          "address": "Sub",
          "email": [
            {
              "key": 0,
              "value": "123"
            },
            {
              "key": 1,
              "value": "123"
            },
            {
              "key": 2,
              "value": "(123"
            }
          ],
          "contact_no": [
            {
              "key": 0,
              "value": "123"
            },
            {
              "key": 1,
              "value": "123"
            },
            {
              "key": 2,
              "value": "123"
            }
          ],
          "description": ""
        }
      ]
    },
    {
      "id": "2",
      "directory_name": "Directory 2",
      "details": [
        {
          "sub_directory_name": "Sub Directory 2",
          "address": "Sub",
          "email": [
            {
              "key": 0,
              "value": "test"
            }
          ],
          "contact_no": [
            {
              "key": 0,
              "value": "test"
            },
            {
              "key": 1,
              "value": "test"
            }
          ],
          "description": ""
        },
        {
          "sub_directory_name": "Sub Directory 3",
          "address": "test",
          "email": [
            {
              "key": 0,
              "value": "tset"
            }
          ],
          "contact_no": [
            {
              "key": 0,
              "value": "test"
            },
            {
              "key": 1,
              "value": "test"
            },
            {
              "key": 2,
              "value": "test"
            }
          ],
          "description": ""
        },
        {
          "sub_directory_name": "Sub Directory 3",
          "address": "test",
          "email": [
            {
              "key": 0,
              "value": "test"
            }
          ],
          "contact_no": [
            {
              "key": 0,
              "value": "test"
            }
          ],
          "description": ""
        }
      ]
    }
  ]
}

it really looks complicated. I need to get the email and contact_no to the details

this is the code that I had currently.

I am using volley.

      CustomRequest stringRequest = new CustomRequest(Request.Method.POST, WebConfig.directories, null,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response)
                    {

                        try {

                            // Get the object data array from response
                            JSONArray dataArray = response.getJSONArray("data");

                            for (int data = 0; data < dataArray.length(); data++) {

                                // Get the data object and save the common id and directory name for each of the details
                                JSONObject dataObject = dataArray.getJSONObject(data);
                                JSONArray detailsArray = dataObject.getJSONArray("details");

                                Integer ID = dataObject.getInt("id");
                                String DirName = dataObject.getString("directory_name");

                                for (int j = 0;j <detailsArray.length();j++) {

                                    DirectoryModel details = new DirectoryModel();
                                    details.setId(ID);
                                    details.setDirectory_name(DirName);

                                    JSONObject detailObject = detailsArray.getJSONObject(j);

                                    details.setSub_directory_name(detailObject.getString("sub_directory_name"));

                                    JSONArray emailsArray = detailObject.getJSONArray("email");


                                    ArrayList<Email> emailArrayList = new ArrayList<>();
                                    for (int k = 0; k <emailsArray.length();k++){
                                        Email email = new Email();
                                        JSONObject emailObject = emailsArray.getJSONObject(k);
                                        email.setKey(emailObject.getString("key"));
                                        email.setValue(emailObject.getString("value"));
                                        details.setEmailArrayList(emailArrayList);
                                    }


                                    JSONArray contactArray = detailObject.getJSONArray("contact_no");

                                    ArrayList<ContactNo> contactNoArrayList = new ArrayList<>();
                                    for (int m = 0; m <contactArray.length();m++){
                                        ContactNo contactNo = new ContactNo();
                                        JSONObject mobileObject = emailsArray.getJSONObject(m);
                                        contactNo.setKey(mobileObject.getString("key"));
                                        contactNo.setValue(mobileObject.getString("value"));
                                        details.setContactNoArrayList(contactNoArrayList);
                                    }

                                    directoryList.add(details);

                                }

                                adapter.notifyDataSetChanged();
                                directoryRecyclerView.setVisibility(View.VISIBLE);

                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        })

I know that my code is still invalid, how can I implement it through my code the problem that I have. any help would be really appreciated.

How to solve:
  • Try this one might help you
  • First Create model or pojo class that contains details

    Details.class //model or pojo class

    public class Details {
    
    String sub_directory_name;
    String address;
    ArrayList<Email> emailArrayList;
    ArrayList<ContactNo> contactNoArrayList;
    
    public String getSub_directory_name() {
        return sub_directory_name;
    }
    
    public void setSub_directory_name(String sub_directory_name) {
        this.sub_directory_name = sub_directory_name;
    }
    
    public String getAddress() {
        return address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }
    
    public ArrayList<Email> getEmailArrayList() {
        return emailArrayList;
    }
    
    public void setEmailArrayList(ArrayList<Email> emailArrayList) {
        this.emailArrayList = emailArrayList;
    }
    
    public ArrayList<ContactNo> getContactNoArrayList() {
        return contactNoArrayList;
    }
    
    public void setContactNoArrayList(ArrayList<ContactNo> contactNoArrayList) {
        this.contactNoArrayList = contactNoArrayList;
    }
    }
    

-In above model or pojo class you need to declare another two model or pojo classes of ContactNo and Email.

Email.class //email model or pojo class

public class Email {

String key;
String value;

public String getKey() {
    return key;
}

public void setKey(String key) {
    this.key = key;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}   
}

ContactNo.class //contactno model or pojo class

public class ContactNo {

String key;
String value;

public String getKey() {
    return key;
}

public void setKey(String key) {
    this.key = key;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

}
  • Then you have to call your api then First declare first arraylist which contains Details then for loop is called in that for loop you have to store data.

    ArrayList<Details> detailsArrayList = new ArrayList<>();
    JsonArray jdetaul = response.body().get("data").getAsJsonArray();
    
    
    
    for (int i = 0; i < jdetaul.size(); i++) {
    
    
        JsonObject object = jdetaul.get(i).getAsJsonObject();
        JsonArray jdetails = object.get("details").getAsJsonArray();
    
    
        for (int j = 0;j <jdetails.size();j++){
            JsonObject detailobj = jdetails.get(j).getAsJsonObject();
            Details details = new Details();
            details.setAddress(detailobj.get("address").getAsString());
            details.setSub_directory_name(detailobj.get("sub_directory").getAsString());
    
    
    
            JsonArray jemail = detailobj.get("email").getAsJsonArray();
    
            ArrayList<Email> emailArrayList = new ArrayList<>();
            for (int k = 0; k <jemail.size();k++){
                JsonObject emailobject = jemail.get(k).getAsJsonObject();
                Email email = new Email();
                email.setKey(emailobject.get("key").getAsString());
                email.setValue(emailobject.get("value").getAsString());
                details.setEmailArrayList(emailArrayList);
            }
    
            JsonArray jcontact_noarray = detailobj.get("contact_no").getAsJsonArray();
    
            ArrayList<ContactNo> contactNoArrayList = new ArrayList<>();
            for (int k = 0; k <jcontact_noarray.size();k++){
    
                JsonObject contactobj = jcontact_noarray.get(k).getAsJsonObject();
                ContactNo contactNo = new ContactNo();
                contactNo.setKey(contactobj.get("key").getAsString());
                contactNo.setValue(contactobj.get("value").getAsString());
                details.setContactNoArrayList(contactNoArrayList);
            }
            detailsArrayList.add(details);
        }
    
    }
    

###

For email and contact, you need to first store them into a JSON array after get their value.

 directoryList.add(new DirectoryModel(
                                    object.getInt("id"),
                                    object.getString("directory_name"),
                                    object.getString("sub_directory_name"),
                                    object.getString("address"),                                        
object.getJSONArray("email").getJSONObject(0).getString("value"),
object.getJSONArray("contact_no").getJSONObject(0).getString("value"), 
                                    object.getString("description")
                            ));

As shown in your JSON this is an array of the email of you want both emails from single JSON object then you need to write code for index 2 as well, also you can use a loop for this.

###

You can use POJO Generator1 orPOJO Generator2 to convert your JSON data into POJO classes in java. After that you can parse JSON data as specified by Dhaval.

###

try bellow code maybe help you

CustomRequest stringRequest = new CustomRequest(Request.Method.POST, WebConfig.directories, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {

                            JSONArray details = response.getJSONArray("data");

                            for (int i = 0; i < details.length(); i++) {
                                int id = 0;
                                String directory_name = "";
                                try {
                                    JSONObject dataObject = details.getJSONObject(i);
                                    if (dataObject.has("id")) {
                                        id = dataObject.getInt("id");
                                    }
                                    if (dataObject.has("directory_name")) {
                                        directory_name = dataObject.getString("directory_name");
                                    }
                                    if (dataObject.has("details")) {
                                        JSONArray arraySubData = dataObject.getJSONArray("details");
                                        for (int pos = 0; pos < details.length(); pos++) {
                                            JSONObject subDataObj = arraySubData.getJSONObject(pos);
                                            String sub_directory_name = "";
                                            String address = "";
                                            String email = "";
                                            String contact_no = "";
                                            String description = "";
                                            if (subDataObj.has("sub_directory_name")) {
                                                sub_directory_name = subDataObj.getString("sub_directory_name");
                                            }
                                            if (subDataObj.has("address")) {
                                                address = subDataObj.getString("address");
                                            }
                                            if (subDataObj.has("description")) {
                                                description = subDataObj.getString("description");
                                            }

                                            if (subDataObj.has("email")) {
                                                JSONArray emailArray = subDataObj.getJSONArray("email");
                                                for (int ke = 0; ke < emailArray.length(); ke++) {
                                                    try {
                                                        if (ke == 0) {
                                                            email = emailArray.getJSONObject(ke).getString("value");
                                                        } else {
                                                            email = email + "," + emailArray.getJSONObject(ke).getString("value");
                                                        }

                                                    } catch (JSONException en) {
                                                        en.printStackTrace();
                                                    }
                                                }
                                            }
                                            if (subDataObj.has("contact_no")) {
                                                JSONArray numberArray = subDataObj.getJSONArray("contact_no");
                                                for (int ke = 0; ke < numberArray.length(); ke++) {
                                                    try {
                                                        if (ke == 0) {
                                                            contact_no = numberArray.getJSONObject(ke).getString("value");
                                                        } else {
                                                            contact_no = contact_no + "," + numberArray.getJSONObject(ke).getString("value");
                                                        }

                                                    } catch (JSONException en) {
                                                        en.printStackTrace();
                                                    }
                                                }
                                            }


                                            directoryList.add(new DirectoryModel(
                                                    object.getInt(id),
                                                    object.getString(directory_name),
                                                    object.getString(sub_directory_name),
                                                    object.getString(address),
                                                    object.getString(email),
                                                    object.getString(contact_no),
                                                    object.getString(description)
                                            ));
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                            adapter.notifyDataSetChanged();
                            directoryRecyclerView.setVisibility(View.VISIBLE);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        })

If I am putting this all parsed data new object then look like bellow

[
  {
    "id": 1,
    "directory_name": "Directory 1",
    "sub_directory_name": "Sub Directory 1",
    "address": "sub",
    "email": "123",
    "contact_no": "123",
    "description": ""
  },
  {
    "id": 1,
    "directory_name": "Directory 1",
    "sub_directory_name": "Sub Directory 2",
    "address": "National",
    "email": "123",
    "contact_no": "123",
    "description": ""
  },
  {
    "id": 2,
    "directory_name": "Directory 2",
    "sub_directory_name": "Sub Directory 2",
    "address": "Sub",
    "email": "test",
    "contact_no": "test,test",
    "description": ""
  },
  {
    "id": 2,
    "directory_name": "Directory 2",
    "sub_directory_name": "Sub Directory 3",
    "address": "test",
    "email": "tset",
    "contact_no": "test,test,test",
    "description": ""
  }
]

###

In your case, Details is a field of data. So you cannot get the details fields as if they were data fields. You are missing some steps in the response JSON tree parsing.
The object we are parsing has this shape:

    data array : [
        data_object1 {
            field1,
            field2,
            details_array [
                details_object1 {
                    field1,
                    ...
                    email_array [email1, email2...],
                    contact_no_array [no1, no2..],
                    ...
                },
                details_object2
            ],
            ...
        },
        {data_object2},
        ...
    ],

So solution needs to be aware of this structure like this:

// Get the object data array from response
JSONArray dataArray = response.getJSONArray("data");

for (int data = 0; data < dataArray.length(); data++) {
    // Get the data object and save the common id and directory name for each of the details
    JSONObject dataObject    = dataArray.getJSONObject(data);
    String     commonID      = dataObject.getInt("id");
    String     commonDirName = dataObject.getString("directory_name");
    // Here we check if the field exists before accesing it
    if (dataObject.has("details")) {
        JSONArray detailsArray = dataObject.getJSONArray("details");
        // We have to iterate the details array and add a directory model for each detail found
        for(int dtl = 0; dtl < detailsArray.length(); dtl++) {     
            JSONObject detailObject = detailsArray.getJSONObject(dtl);
            // We need to extract the emails
            String emails = "";
            JSONArray emailsArray = detailObject.getJSONArray("email");
            int lEmails = emailsArray.length()
            for(int e = 0; e < lEmails; e++) {
                JSONObject emailObject = emailsArray.getJSONObject(e);
                emails += emailObject.getString("value");
                if(e < lEmails - 1) emails += ", ";
            }
            // And contact numbers too:
            String numbers = "";
            JSONArray numbersArray = detailObject.getJSONArray("contact_no");
            int lNumbers = numbersArray.length()
            for(int n = 0; n < lNumbers; n++) {
                JSONObject numberObject = numbersArray.getJSONObject(n);
                numbers += numberObject.getString("value");
                if(n < lNumbers - 1) numbers += ", ";
            }
            // Now we can build the directory model and add to our list :)
            directoryList.add(new DirectoryModel(
                commonID,
                commonDirName,
                detailObject.getString("sub_directory_name"),
                detailObject.getString("address"),
                emails,
                numbers,
                detailObject.getString("description")
            ));
        }
    }

    adapter.notifyDataSetChanged();
    directoryRecyclerView.setVisibility(View.VISIBLE);

}

Leave a Reply

Your email address will not be published. Required fields are marked *