Sainita
Sainita

Reputation: 362

Unable to Parse JSONArray cannot be converted to JSONObject

This is my JSON (full JSON is here : https://pastebin.com/kyPMWcTT):

 "replies": [
        [
           {
              "id": 2,
              "parent": 0,
              "author": 1,
              "author_name": "admin",
              "author_url": "http://localhost/wordpress",
              "date": "2021-05-02T08:38:00",
              "content": {
                 "rendered": "<p>Nice Blog, Awesome !</p>\n"
              },
              "link": "http://localhost/wordpress/2021/05/01/one-pot-thai-style-rice-noodles/#comment-2",
              "type": "comment",
             
              }
        ]

I am trying to get the rendered item which is inside the content Object . This is the Code i have tried :

   JSONArray replyArray = embeddedObject.getJSONArray("replies");
                            for (int j = 0; j < replyArray.length(); j++) {
                                JSONObject contentObject = replyArray.getJSONObject(j);
                                JSONObject getContent = contentObject.getJSONObject("content");
                                String reply = getContent.getString("rendered");
                                Log.e("Reply is", reply);
                            }

But, the Logcat output is :

Value at 0 of type org.json.JSONArray cannot be converted to JSONObject

How to solve this problem ? What am i doing wrong ? Please Guide

Upvotes: 0

Views: 39

Answers (1)

Navjot
Navjot

Reputation: 1294

What's Happening?

We are trying to fetch the JSONObject immediately after replies JSONArray. But, the actual content lies in the following hierarchy.

replies JSONObject -> JSONArray -> JSONArray -> ContentObject -> Content

Solution

Replace this

JSONArray replyArray = embeddedObject.getJSONArray("replies");
for (int j = 0; j < replyArray.length(); j++) {
      JSONObject contentObject = replyArray.getJSONObject(j);
      JSONObject getContent = contentObject.getJSONObject("content");
      String reply = getContent.getString("rendered");
      Log.e("Reply is", reply);
}

With this

JSONArray replyArray = embeddedObject.getJSONArray("replies");
for (int j = 0; j < replyArray.length(); j++) {
      JSONArray replySubArray = replyArray.getJSONArray(j);
      for (int i = 0; i < replySubArray.length(); j++) {
            JSONObject contentObject = replySubArray.getJSONObject(i);
            JSONObject getContent = contentObject.getJSONObject("content");
            String reply = getContent.getString("rendered");
            Log.e("Reply is", reply);
      }
}

Upvotes: 1

Related Questions