无法访问JSON数组Android的某些成员

时间:2017-01-28 15:51:28

标签: android json okhttp3

我有JSON array喜欢这个

[
  {
    "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"
  }
]

我正在使用OKhttp3来检索我的数据,例如

 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);
     ...........

JSONObeject到位i的对象只包含

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

但我希望能够做到这样的事情object.setString("name") 或者到object地方的i获取姓名,图片和地址

1 个答案:

答案 0 :(得分:3)

您的所有对象都没有let(:foo) { Foo.create() } 键值对,因此您可以使用optStringexpect(foo).not_to receive :bar

name

或者您可以使用It returns an empty string if there is no such key

has
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
      }
}
Determine if the JSONObject contains a specific key.