Skip to content Skip to sidebar Skip to footer

Unable To Parse Json In Android

I want to parse the following JSON response. I couldn't extract the JSONArray which is inside the JSON object. I'm a novice to JSON parsing, any help would be appreciated. { 'R

Solution 1:

Basic code for implementing JSON Parsing is like:

JsonObject objJSON = newJSONObject("YourJSONString");

JSONObject objMain = objJSON.getJSONObject("NameOfTheObject");
JSONArray objArray = objMain.getJSONArray("NameOfTheArray");  // Fetching array from the object

Update:

Based on your comment, i can see you haven't fetched JSONArray "Data", without it you are trying to fetch values/attributes of a particular object:

JSONObject jObj = jsonObj.getJSONfromURL(category_url); 
JSONObject menuObject = jObj.getJSONObject("Result"); String attributeId = menuObject.getString("Data");

String attributeId = menuObject.getString("Data");   // Wrong codeJSONArray objArray = menuObject.getJSONArray("Data"); // Right code

Solution 2:

I like to use the GSON library: http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

It's a JSON-parsing library by Google.

Solution 3:

OK, step by step:

String json ="{\"Result\":{\"Data\":[{\"id\":\"1\",\"Name\":\"ABC\",\"release\":\"8\",\"cover_image\":\"august.png\",\"book_path\":\"Aug.pdf\",\"magazine_id\":\"1\",\"Publisher\":\"XYZ\",\"Language\":\"Astrological Magazine\",\"Country\":\"XYZ\"},{\"id\":\"2\",\"Name\":\"CDE\",\"release\":\"8\",\"cover_image\":\"august2012.png\",\"book_path\":\"aug.pdf\",\"magazine_id\":\"2\",\"Publisher\":\"XYZ\",\"Language\":\"Astrological Magizine\",\"Country\":\"XYZ\"}]}}";

try
{
    JSONObject o = new JSONObject(json);
    JSONObject result = o.getJSONObject("Result");
    JSONArray data = result.getJSONArray("Data");

    for (int i =0; i < data.length(); i++)
    {
        JSONObject entry = data.getJSONObject(i);
        String name = entry.getString("Name");
        Log.d("name key", name);
    }   
}
catch (JSONException e)
{
    e.printStackTrace();
}

Json is hardcoded, so I had to escape it. This code gets result object and then data array. A loop goes through an array and gets a value of Name.

I got in LogCat: ABC CDE

Note that you should surround it with try-catch or add throws to a method.

Post a Comment for "Unable To Parse Json In Android"