styx
styx

Reputation: 1917

Can't access some member of JSON array Android

I have JSON array like this

[
  {
    "ride_id": "48",
    "user_id": "22",
    "event_id": "42",
    "driver_id": "0",
    "pick_up_location": "11111"
  },
  {
    "ride_id": "48",
    "user_id": "21",
    "event_id": "42",
    "driver_id": "0",
    "pick_up_location": "11111"
  },
  {
    "name": "ofir rosner",
    "image": "",
    "address": "Yokne\\'am Illit, Israel"
  },
  {
    "name": "hhhh",
    "image": "profilePictureOfUserId22.JPG",
    "address": "ffffd"
  }
]

im using OKhttp3 to retrieve my data like

 Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
    JSONObject object = array.getJSONObject(i);
     ...........

but the object of JSONObeject in place i only contains

{"ride_id":"50","user_id":"2","event_id":"44","driver_id":"0","pick_up_location":"11111"}

but I want to be able to do something like this object.setString("name") or to get to the object in the place i for name, image and address

Upvotes: 2

Views: 155

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

Your all object don't have name key-value pair so you can use optString , It returns an empty string if there is no such key

JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
    JSONObject object = array.getJSONObject(i);
    String name = object.optString("name");

    // optionally use object.optString("name","No Name Found");
    // To display some default string as name 

    if(!name.isEmpty()){
        // we got the data , use it
        Log.i("name is ",name); // display data in logs
      }
}

or you can use has which Determine if the JSONObject contains a specific key.

JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
    JSONObject object = array.getJSONObject(i);
    String name;
    if(object.has("name")){
          name = object.optString("name"); // got the data , use it
      }
}

{   // this object has no "name" key-value pair and so does some other object
    "ride_id": "48",
    "user_id": "22",
    "event_id": "42",
    "driver_id": "0",
    "pick_up_location": "11111"
  }

Upvotes: 3

Related Questions