简体   繁体   中英

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?

verseReaders是一个JSONArray ,因此您需要迭代(或获取第一个) JSONObject ,然后从该对象获取字符串。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM