ashokgujju
ashokgujju

Reputation: 320

How to parse specific JSON data in Android?

This is my JSON data from a URL:

[
  { "title" : "65th Issue", "author": "అశోక్"},
  { "title" : "64th Issue", "author": "రాము" },
  { "title" : "63rd Issue", "author": "శ్రీను" }
]

It is looking like a JSONArray but it does not have its name (Array name) to access. Could anyone tell me how can I parse this JSON data in android?

Parsing Code

InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);

int contentLength = connection.getContentLength();
char [] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);

try{
    JSONArray jArray = new JSONArray(responseData);
    for(int i = 0; i < jArray.length(); i++) {
        String title = jArray.getJSONObject(i).getString("title");
    }
} catch (JSONException e) {
    Log.v(TAG, "JSON EXCEPTION");
}

Upvotes: 0

Views: 134

Answers (1)

Shivam Verma
Shivam Verma

Reputation: 8023

String jsonString = ...; //This contains the above mentioned String.

For JSON String, [] denotes an array, an {} denotes an object. In your case, the string starts with a [] thats means its an array, so we first get the JSONArray.

JSONArray jArray = new JSONArray(jsonString);

Now, if you see, the array has multiple strings beginning and ending with {}, that means that the array has multiple objects. So we run a loop over the array length to extract each object and then the key - value from the object.

for(int i = 0; i < jArray.length(); i++) {
    String title = jArray.getJSONObject(i).getString("title");
}

So, the complete code will be something like this :

String jsonString = ...; //This contains the above mentioned String.
JSONArray jArray = new JSONArray(jsonString);
for(int i = 0; i < jArray.length(); i++) {
    String title = jArray.getJSONObject(i).getString("title");
}

Edit 2 :

String jsonString = "[\r\n  { \"title\" : \"65th Issue\", \"author\": \"\u0C05\u0C36\u0C4B\u0C15\u0C4D\"},\r\n  { \"title\" : \"64th Issue\", \"author\": \"\u0C30\u0C3E\u0C2E\u0C41\" },\r\n  { \"title\" : \"63rd Issue\", \"author\": \"\u0C36\u0C4D\u0C30\u0C40\u0C28\u0C41\" }\r\n]";

    try {
        JSONArray jArray = new JSONArray(jsonString);
        for (int i = 0; i < jArray.length(); i++) {
            String title = jArray.getJSONObject(i).getString("title");
            Log.d(LOGTAG, title);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

Upvotes: 2

Related Questions