skip to Main Content

I’m trying to print out an object in the JSON using Facebook Graph API.

Here’s my code:

try{
    JSONArray data = innerJson.getJSONArray("data");
    Log.d("innerDataLength", String.valueOf(data.length()));

    for (int i = 0; i<data.length(); i++) {
        String message = data.getJSONObject(i).getString("message");
        Log.d("message", message);
    }
} catch (JSONException e) {
    Log.d("exception", e.getMessage());
}

Here’s output:

D/innerDataLength: 25
D/message: "blah blah blah"
D/exception: No value for message

As you can see the condition i.e. data.length() is 25 then why am I getting the message printed out only once?

2

Answers


  1. Note that you get an exception:

    D/exception: No value for message

    It indicates that the second object in JSONArray has no message property. Looks like it’s optional, so you need to check whether message property exists first.

    Update:

    try{
        JSONArray data = innerJson.getJSONArray("data");
        Log.d("innerDataLength", String.valueOf(data.length()));
    
        for (int i = 0; i < data.length(); i++) {
            JSONObject obj = data.getJSONObject(i);
            if (obj.has("message")) {
                String message = obj.getString("message");
                Log.d("message", message);
            }
            if (obj.has("story")) {
                String story= obj.getString("story");
                Log.d("story", story);
            }
        }
    } catch (JSONException e) {
        Log.d("exception", e.getMessage());
    }
    
    Login or Signup to reply.
  2. some of object in innerJson.getJSONArray(“data”) array don’t has message

    to check what i say comment the line inside loop and just print i will get 0 to 24

    to avoid that surrounded the statment of parsing message with try and catch to avoid parsing object that not contain message

    you can also print data.getJSONObject(i).toString to see parsing object

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search