X09
X09

Reputation: 3956

How to Parse this json object nested in json array

I am using this code

private void parseData(JSONArray array){
        Log.d(TAG, "Parsing array");


        for(int i = 0; i<array.length(); i++) {
            bookItems bookItem = new bookItems();
            JSONObject jsonObject = null;
            try {
                jsonObject = array.getJSONObject(i);

                JSONObject bookChapter = jsonObject.getJSONObject("chapter");
                bookItem.setbook_subtitle(bookChapter.getString("subtitle"));

                JSONObject chapVerses = jsonObject.getJSONObject("verses");
                JSONArray verseReaders = chapVerses.getJSONArray("readers");
                JSONObject readersNum = verseReaders.getJSONObject("number");
                verseReadNum = readersNum;


            } catch (JSONException w) {
                w.printStackTrace();
            }
            mbookItemsList.add(bookItem);

        } 

    }

to parse this json.

[
  {
    "chapter": {
      "subtitle": "Something happened in this in this chapter"
    },
    "verses": {
      "about": [
        {
          "In this verse, a lot of things happened yes a lot!"
        }
      ],
      "readers": [
        {
          "read": false,
          "number": "No body has read this verse yet"
        }
      ],

    }
  }, 
  ...]

I am getting the "subtitle" correctly but I am having didfficulty getting "number".

From line JSONObject readersNum = verseReaders.getJSONObject("number"); Android studio is complaining that getJSONOBJECT (int) in JSONArray cannnot be applied to (java.lang.String)

Please, how do I properly parse this?

Upvotes: 0

Views: 59

Answers (2)

Maxim G
Maxim G

Reputation: 1489

You have to use nested loops. Just add one more for for "readers".

Upvotes: 0

Dan Harms
Dan Harms

Reputation: 4840

verseReaders is a JSONArray, so you need to iterate over (or take the first) JSONObject and then get the string from that object.

String readersNum = verseReaders.getJSONObject(0).getString("number");

Upvotes: 1

Related Questions