这是解析json的正确方法吗?

时间:2017-02-01 04:46:29

标签: android json gridview

我正在将json值解析为gridView,但不知何故它在gridView中没有显示任何值,我在json代码中感到困惑,因为我觉得我在这段代码中遗漏了一些东西......请检查:

private void getData() {
        //Showing a progress dialog while our app fetches the data from url
        final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
        String DATA_URL = "http://........nList";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
                        loading.dismiss();
                        try {
                            JSONArray json = new JSONArray(response);
                            for (int i = 0; i < json.length(); i++) {
                                //Creating a json object of the current index
                                JSONObject obj = null;
                                try {
                                    //getting json object from current index
                                    obj = json.getJSONObject(i);
                                    //getting image url and title from json object
                                    pid.add(obj.getInt(String.valueOf(TAG_PID)));
                                    pname.add(obj.getString(TAG_PNAME));
                                    pdetails.add(obj.getString(TAG_PDETAILS));
                                    pmobile.add(obj.getString(TAG_MOBILE));
                                    pemail.add(obj.getString(TAG_EMAIL));
                                    images.add(obj.getString(TAG_IMAGE_URL));
                                    names.add(obj.getString(TAG_NAME));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //Creating GridViewAdapter Object
                        PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);

                        //Adding adapter to gridview
                        pmpigeonlistadapter.notifyDataSetChanged();
                        gridView.setAdapter(pmpigeonlistadapter);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("country", PostCountry);
                params.put("strain", PostStrain);
                params.put("distance", PostDistance);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);


    }

这是我的json输出:

{
  "status_code": 200,
  "status": "OK",
  "status_message": "Success",
  "pigeon_list": [
    {
      "id": "1",
      "pigeon_name": "sofiee",
      "auth_token": "58809c7129a5a",
      "country_code": "AE",
      "strain_id": "75",
      "distance": "3",
      "pigeon_price": "50.00",
      "pigeon_details": "One of the best ",
      "image": "http:.98a8ac5.jpeg",
      "pedigree_image": "http://...1.jpeg",...
      "status": "",
      "created": "2017-01-19 16:52:14",
      "updated": "0000-00-00 00:00:00",
      "strain_name": "Janssen/gaston wowers ",
      "usr_mobile": "+971/505040009",
      "usr_image": "http://....19a.jpeg",
      "usr_email": "...edo@gmail.com"
    },

我也会在吐司中得到回应,只有json问题才会出现......

这是php代码:

public function searchPigeonList()
    {
        $data = (array)$this->request->input('json_decode');

        $returnArr = $this->resp_arr;
        $returnArr['pigeon_list'] = array();
        $conn = ConnectionManager::get('default');

        $query = "SELECT `pg`.*,`ps`.name as strain_name,`us`.mobile as usr_mobile,`us`.image as usr_image,`us`.email as usr_email FROM 
`pigeons` as `pg` INNER JOIN `users` as `us` ON `pg`.`auth_token` = `us`.`uniq_id` INNER JOIN `pigeon_strain` as `ps` ON `ps`.`id` = `pg`.`strain_id` ";

//            $query .= "WHERE `pg`.`country_code` = '".$data['country_code']."' ";
        $cnt_cd = $data['country_code'];
        $str_id = $data['strain_id'];
        $dst = $data['distance'];

        $conditions = array();
        if($cnt_cd !="") {
            $conditions[] = "`pg`.country_code='$cnt_cd'";
        }
        if($str_id !="") {
            $conditions[] = "`pg`.strain_id='$str_id'";
        }
        if($dst !="") {
            $conditions[] = "`pg`.distance='$dst'";
        }
        if (count($conditions) > 0) {
            $query .= " WHERE " . implode(' AND ', $conditions);
            $query .= " AND `pg`.status='approved'";
        }
//echo $query;exit;
        $stmt = $conn->execute($query);
        $returnArr['status_code'] = 200;
        $returnArr['status'] = "OK";
        $returnArr['status_message'] = "Success";
        $returnArr['pigeon_list'] = $stmt ->fetchAll('assoc');
        if ($this->request->is('post')) {
            echo json_encode($returnArr);
            exit;
        }

    }

2 个答案:

答案 0 :(得分:1)

try {
    JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
    for (int i = 0; i < json.length(); i++) {
        JSONObject obj = null;
        try {
            obj = json.getJSONObject(i);
            pid.add(obj.getInt("id")); 
            pname.add(obj.getString("pigeon_name"));
            pdetails.add(obj.getString("pigeon_details"));
            pmobile.add(obj.getString("usr_mobile"));
            pemail.add(obj.getString("usr_email"));
            images.add(obj.getString("usr_image"));
            names.add(obj.getString("pigeon_name"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}catch(JSONException je){
    je.printStackTrace();
}catch(Exception e){
    e.printStackTrace();
}

尝试替换

答案 1 :(得分:0)

试试这个。

 public void onResponse(String response) {
                    //Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
                    loading.dismiss();
                    try {
                        JSONObject  responseObject=new JSONObject(response);
                        JSONArray json = responseObject.getJSONArray("pigeon_list");
                        for (int i = 0; i < json.length(); i++) {
                            //Creating a json object of the current index
                            JSONObject obj = null;
                            try {
                                //getting json object from current index
                                obj = json.getJSONObject(i);
                                //getting image url and title from json object
                                pid.add(obj.getInt(String.valueOf(TAG_PID)));
                                pname.add(obj.getString(TAG_PNAME));
                                pdetails.add(obj.getString(TAG_PDETAILS));
                                pmobile.add(obj.getString(TAG_MOBILE));
                                pemail.add(obj.getString(TAG_EMAIL));
                                images.add(obj.getString(TAG_IMAGE_URL));
                                names.add(obj.getString(TAG_NAME));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    //Creating GridViewAdapter Object
                    PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);

                    //Adding adapter to gridview
                    pmpigeonlistadapter.notifyDataSetChanged();
                    gridView.setAdapter(pmpigeonlistadapter);

                }