2

I am trying to make an android app that fetch posts from my wordpress blog that displays the information in a list. I am able to get the results like title, description,etc but i am not able to get nested object "tags" from the JSON result. So, can you explain me how i can get the tag names from the JSON result from this JSON Response.

I am trying to use the following code :

JSONObject root = new JSONObject(postJSON);
        JSONArray postsArray = root.getJSONArray("posts");


        for (int i = 0; i < postsArray.length(); i++) {
            // Get a single post at position i within the list of earthquakes
            JSONObject currentPost = postsArray.getJSONObject(i);

            String title = currentPost.getString("title");
            Log.e(LOG_TAG, "title is " + title);

            JSONObject tags = currentPost.getJSONArray("tags").getJSONObject(0);
            String tag = tags.getString("name");
            Log.e(LOG_TAG, "tag is " + tag);

            Post post = new Post(title,"123", tag);
            posts.add(post);
        }

But the logcat is showing that the value can't be converted to JSONArray.

1 Answer 1

1

The issue is that tags is actually another JSON object not a JSON array. You need to do the following:

JSONObject tags = currentPost.getJSONObject("tags").getJSONObject(0);
String tag = tags.getString("name");
Log.e(LOG_TAG, "tag is " + tag);

Just remember JSON arrays are always denoted by [] and objects by {}.

Hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

you are right, BUT now the problem is that you can't use int as an input for JSONObject.
Ah, this question may help you? stackoverflow.com/questions/22606572/…

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.