如何从json数组中获取整数值

时间:2014-12-25 06:16:00

标签: android json

我的json的响应如下,我正在尝试parse data,但是当我解析user_photo_id时,它会JSONException:No values for user_photo_id,任何人都可以告诉我吗?

{  
  "user_login_id": "2650",  
  "user_total_photo": "3",  
  "max_upload_photo": "3",  
  "image_list": [  
    {  
      "user_photo_id": 334,  
      "status": "Approved",  
      "photo": ""  
    },  
    {  
      "user_photo_id": 394,  
      "status": "Approved",  
      "photo": ""  
    },  
    {  
      "user_photo_id": 398,  
      "status": "Admin Approve Remaining",  
      "photo": ""  
    }  
  ]  
}

我的java代码:

 class LoadImages extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {


         String photoid;
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
            String jsonStr = sh.makeServiceCall(IMAGE_URL, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);


                try {
                    jsonObj = new JSONObject(jsonStr);


                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(IMAGE_USERLOGIN_ID, jsonObj.getString(IMAGE_USERLOGIN_ID));
                        map.put(IMAGE_TOTAL_PHOTO,jsonObj.getString(IMAGE_TOTAL_PHOTO));
                        map.put(IMAGE_MAX_UPLOAD, jsonObj.getString(IMAGE_MAX_UPLOAD));
                        /*map.put(IMAGE_USER_PHOTOID, jsonObj.getString(IMAGE_USER_PHOTOID));
                        map.put(IMAGE_STATUS, jsonObj.getString(IMAGE_STATUS));
                        map.put(IMAGE_PHOTO, jsonObj.getString(IMAGE_PHOTO));
                        */




                        image_list = (JSONArray) jsonObj.get(IMAGE_LISTING);
                        for(int i=0;i< image_list.length();i++)
                        {
                           photoid += image_list.get(i);
                           Log.d("mylog", "initial marital  = " + photoid);

                        }

                          getActivity().runOnUiThread(new  Runnable() 
                     {
                        @Override
                        public void run() 
                        {
                            Intent intent=new Intent(getActivity(),PhotoView.class);
                            intent.putExtra("id", id);
                            intent.putExtra("totals", totalphota);
                            intent.putExtra("maxs", maximumphota);

                            startActivity(intent);
                        } 
                    });
                       /* image_list = (JSONArray) jsonObj.get("user_photo_id");
                        image_list=(JSONArray) jsonObj.get(IMAGE_STATUS);
                        image_list=(JSONArray)jsonObj.get(IMAGE_PHOTO);
                        for(int i=0;i< image_list.length();i++)
                        {
                          String photoid=

                        }*/

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            return data;
        }


        protected void onPostExecute(ArrayList<HashMap<String,String>> result) {

            super.onPostExecute(result);


            // dismiss the dialog after getting all albums
            if (pDialog.isShowing())
                pDialog.dismiss();
            // updating UI from Background Thread
            /*Intent mIntent = new Intent(getActivity(),Filter.class);
            Bundle extras = mIntent.getExtras();
            try {
                extras.putString("radiostatus", jsonObj.getString(FILTER_ALLOW));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  */


        }

    }

2 个答案:

答案 0 :(得分:1)

希望有所帮助。您只需要遵循json字符串的结构。 (json数组包含json对象,因此首先在循环中获取json对象,然后从中获取user_photo_id)

image_list = (JSONArray) jsonObj.get("image_list");
for(int i=0;i< image_list.length();i++)
{
   JSONObject imageListItem = image_list.getJSONObject(i);
   int  userPhotoId = imageListItem.getInt("user_photo_id")
   Log.d("mylog", "i ="+i+" and user_photo_id =" + userPhotoId);
}

答案 1 :(得分:1)

image_list = (JSONArray) jsonObj.get(IMAGE_LISTING);
for(int i=0;i< image_list.length();i++)
{
    photoid += image_list.get(i);//here you made a mistake
    Log.d("mylog", "initial marital  = " + photoid);

}

在你的json中,image_list是JsonArray,但是这个数组中的每个元素都是一个JsonObject,所以你将得到一个JsonObject使用image_list.get(i)而不是int。所以你应该做更多的任务:

image_list = jsonObj.getJSONArray(IMAGE_LISTING);
for(int i=0;i< image_list.length();i++)
{
    photoid += image_list.getJSONObject(i).getInt("user_photo_id");
    Log.d("mylog", "initial marital  = " + photoid);

}

更新以将json数据发送到其他活动:

1.创建一个类来存储你的数据:

public class JsonData{
    private JsonObject mData;

    //getter and setter and other function you need
}

2.implements Serializable:

public class JsonData implements Serializable{
    private static final long serialVersionUID = 6037391814333931008L;//It should generate by your IDE
    private JsonObject mData;

    //getter and setter and other function you need
}

3.使用Bundle和Intent在启动Activity时发送Serializable数据

Intent intent = new Intent(Sender.this, Receiver.class); // replace Sender and Receiver with your Activities 
Bundle bundle = new Bundle();
bundle.putSerializable("Your Key", yourDataClass);//replace yourDataClass with your JsonData class
intent.putExtras(bundle);
startActivity(intent);

4.接收其他活动中的数据:

在此活动的onCreate中添加代码:

Bundle bundle = getIntent().getExtras();

    if (bundle != null) {

        Serializable data = bundle.getSerializable("Your Key");

        if (data != null) {
            JsonData jsonData= (JsonData) data;
            //now you have got your data and do whatever you want.
        }
    }

但是,如果Activity为singleTask模式,则步骤4中的代码也应放在onNewIntent中。在这种情况下,您应该在onNewIntent

中保存意图
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    //here to place the code in Step 4 and also place in onCreate function
}