0

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?

3
  • You know, if you use Gson and define a model class, then you wouldn't need to manually parse the Json yourself Commented Apr 19, 2016 at 21:53
  • @cricket_007 I'm using Volley, does it support Gson? Commented Apr 19, 2016 at 21:59
  • Sure, there is even a custom GsonRequest at the bottom of the Volley Documentation Commented Apr 19, 2016 at 22:04

2 Answers 2

1

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");
Sign up to request clarification or add additional context in comments.

4 Comments

Please can you be kind enough to give your answer in code?
Thanks, but just a little explanation. You wrote 0 why not 1 or 2 or any other number?
The 0 means the first JSONObject from the JSONArray
Yes since I wasn't sure how you were intending to use the readers array I just showed it grabbing the first.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.