This question already has answers here:
JSON Array of strings (no objects), extracting data
                                
                                    (3个答案)
                                
                        
                                3年前关闭。
            
                    
它实际上是一个简单的代码,由于缺乏基本知识,我仍然无法解决这个问题。

在我自己的Api上创建Post JSON方法后,得到以下响应

[{"id":"2"}]


我想要实现的是,我想获得这个“ id”的值为“ 2”。

我已经在我的私有void方法中尝试了以下代码

   private void getUserID() {


    StringRequest stringRequest = new StringRequest(Method.POST,Constants.GET_USER_ID,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();

      try {
         JSONObject  jsonRootObject = new JSONObject(strJson);

         //Get the instance of JSONArray that contains JSONObjects
         JSONArray jsonArray = jsonRootObject.optJSONArray("");

         //Iterate the jsonArray and print the info of JSONObjects
         for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            int id = Integer.parseInt(jsonObject.optString("id").toString());
            String idUser = jsonObject.optString("id").toString();


         }
         output.setText(idUser);
      } catch (JSONException e) {e.printStackTrace();}

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                })


        {


            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> map = new HashMap<>();

                map.put(Constants.KEY_A, username);
                map.put(Constants.KEY_B, password);


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


我从here获得它。

这有点浪费,因为我数组中只有一个列表对象,并且我认为for循环在这里并不是很重要。

最佳答案

用以下替换您的try块

  try {
             JSONArray  jsonArray = new JSONArray(response);

                JSONObject jsonObject = jsonArray.getJSONObject(0);
                String idUser = jsonObject.getString("id");
                Log.e("id is: ", idUser);

             }

09-16 19:44