1

I am new to JSON and I am facing hard time looping through the JSONObjects inside the JSONArray for an Android Application that I am building. I would be thankful if posters would givw a brief explanation of the solution as well because I just don't want to copy & paste the code but understand it. Thank You.

API Link: https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories

API Output:

[
{
    "id": 5580,
    "count": 5,
    "description": "",
    "link": "https://spoketest.wordpress.com/category/diversions/",
    "name": "Diversions",
    "slug": "diversions",
    "taxonomy": "category",
    "parent": 0,
    "meta": [],
    "_links": {
        "self": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories/5580"
            }
        ],
        "collection": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories"
            }
        ],
        "about": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/taxonomies/category"
            }
        ],
        "wp:post_type": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/posts?categories=5580"
            }
        ],
        "curies": [
            {
                "name": "wp",
                "href": "https://api.w.org/{rel}",
                "templated": true
            }
        ]
    }
},
{
    "id": 9548,
    "count": 5,
    "description": "",
    "link": "https://spoketest.wordpress.com/category/features/",
    "name": "Features",
    "slug": "features",
    "taxonomy": "category",
    "parent": 0,
    "meta": [],
    "_links": {
        "self": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories/9548"
            }
        ],
        "collection": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories"
            }
        ],
        "about": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/taxonomies/category"
            }
        ],
        "wp:post_type": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/posts?categories=9548"
            }
        ],
        "curies": [
            {
                "name": "wp",
                "href": "https://api.w.org/{rel}",
                "templated": true
            }
        ]
    }
},
{
    "id": 103,
    "count": 10,
    "description": "",
    "link": "https://spoketest.wordpress.com/category/news/",
    "name": "News",
    "slug": "news",
    "taxonomy": "category",
    "parent": 0,
    "meta": [],
    "_links": {
        "self": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories/103"
            }
        ],
        "collection": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories"
            }
        ],
        "about": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/taxonomies/category"
            }
        ],
        "wp:post_type": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/posts?categories=103"
            }
        ],
        "curies": [
            {
                "name": "wp",
                "href": "https://api.w.org/{rel}",
                "templated": true
            }
        ]
    }
},
{
    "id": 660,
    "count": 10,
    "description": "",
    "link": "https://spoketest.wordpress.com/category/people/",
    "name": "People",
    "slug": "people",
    "taxonomy": "category",
    "parent": 0,
    "meta": [],
    "_links": {
        "self": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories/660"
            }
        ],
        "collection": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories"
            }
        ],
        "about": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/taxonomies/category"
            }
        ],
        "wp:post_type": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/posts?categories=660"
            }
        ],
        "curies": [
            {
                "name": "wp",
                "href": "https://api.w.org/{rel}",
                "templated": true
            }
        ]
    }
},
{
    "id": 318,
    "count": 10,
    "description": "",
    "link": "https://spoketest.wordpress.com/category/tech/",
    "name": "Tech",
    "slug": "tech",
    "taxonomy": "category",
    "parent": 0,
    "meta": [],
    "_links": {
        "self": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories/318"
            }
        ],
        "collection": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories"
            }
        ],
        "about": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/taxonomies/category"
            }
        ],
        "wp:post_type": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/posts?categories=318"
            }
        ],
        "curies": [
            {
                "name": "wp",
                "href": "https://api.w.org/{rel}",
                "templated": true
            }
        ]
    }
},
{
    "id": 160479,
    "count": 6,
    "description": "",
    "link": "https://spoketest.wordpress.com/category/traction/",
    "name": "Traction",
    "slug": "traction",
    "taxonomy": "category",
    "parent": 0,
    "meta": [],
    "_links": {
        "self": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories/160479"
            }
        ],
        "collection": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/categories"
            }
        ],
        "about": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/taxonomies/category"
            }
        ],
        "wp:post_type": [
            {
                "href": "https://public-api.wordpress.com/wp/v2/sites/spoketest.wordpress.com/posts?categories=160479"
            }
        ],
        "curies": [
            {
                "name": "wp",
                "href": "https://api.w.org/{rel}",
                "templated": true
            }
        ]
    }
}
]

My Code:

import org.json.JSONException;
import org.json.JSONObject;

public class Category {
private int mCategoryID;
private String mCategoryName;

public static Category fromJSON(JSONArray jsonArray) {
    try {
        Category category = new Category();
        category.mCategoryID = jsonArray.getJSONObject("0").getInt("id");
        category.mCategoryName = jsonArray.getJSONObject("0").getString("name");

        return category;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
}

public int getCategoryID() {
    return mCategoryID;
}

public String getCategoryName() {
    return mCategoryName;
}
}

1 Answer 1

1

Once you've retrieved the response from the API (using AsyncTask), take the response text and create a JSONArray. Then you can loop through the array and extract the categories.

public void onApiResponse(String response) {
    // Create a JSONArray from the response
    JSONArray jsonArray = new JSONArray(response);

    // Create a structure to store all of the categories
    List<Category> categories = new ArrayList<Category>();

    // Loop through the array and parse all the categories
    for (int i = 0; i < jsonArray.length(); i++) {
        // Extract the JSONObject from the index
        JSONObject jsonCategory = jsonArray.getJSONObject(i);

        // Add the category to the list
        categories.add(Category.fromJSON(jsonCategory));
    }

    // Do something with your categories...
}

EDIT: I see you hardcoded some values into your fromJSON, so I thought I'd post a corrected version of that as well.

public static Category fromJSON(JSONObject jsonObject) {
    try {
        Category category = new Category();
        category.mCategoryID = jsonObject.getInt("id");
        category.mCategoryName = jsonObjectgetString("name");

        return category;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

I am using James Smith's Android Asynchronous Http Client library for Async related tasks (link) and it returns JSONObject. My fromJSON method takes that JSONObject as an input parameter which parses the data. Now in your solution I need a String as an input parameter. Can I covert the JSONObject to String using toString() without any adverse effects?
The sample response you've posted is a JSON array, not a JSON object. If you're receiving a JSON object in response, the library is not interpreting the response correctly, or you're interpreting the return value incorrectly. Print out the JSONObject's toString() and compare to the actual text from the API to see what's going wrong.
Oh! I made a mistake. Yes, I get a JSONArray and the input parameter for the fromJSON is JSONArray. But again, can I use toString on the JSONArray without any adverse effect?
In theory, you should be able to, but that introduces a lot of inefficiency where it could be avoided. Take the time to adapt my answer to your code, don't just copy and paste.
OK! Will do. Thank You.
|

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.