【问题标题】:How to Get String from JSON Array [duplicate]如何从 JSON 数组中获取字符串 [重复]
【发布时间】:2016-06-28 05:35:18
【问题描述】:

它实际上是一个简单的代码,因为缺乏基本的我仍然无法处理这个。

在我自己的 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 循环在这里并不重要。

【问题讨论】:

  • strJson 是 JSONArray 而不是 JSONObject 所以这样做:JSONArray jsonArray = new JSONArray(strJson); int _id=jsonArray.getJSONObject(0).getInt("id"); 如果 JSONArray 只包含单个项目,则不需要使用 for-loop
  • 如果你只有一个项目然后删除 jsonarray.. 并做出这样的响应 {"id":"2"}..then get id

标签: android json


【解决方案1】:

将您的 try 块替换为以下内容

  try {
             JSONArray  jsonArray = new JSONArray(response);

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

             }

【讨论】:

  • 有点 android studio 想让我尝试一下,JSONArray jsonArray = null;尝试 { jsonArray = new JSONArray(response);} catch (JSONException e) {e.printStackTrace();} JSONObject jsonObject = null;尝试 { jsonObject = jsonArray.getJSONObject(0);} catch (JSONException e) {e.printStackTrace(); } 字符串 idUser = null;尝试 { idUser =jsonObject.getString("id"); } 捕捉 (JSONException e) {e.printStackTrace(); } Log.e("id 为:", idUser);
  • JSONArray jsonArray = new JSONArray (response); -> AS 建议为它设置 try catch 块。很快直到 String idUser
  • @GideonStevenTobing 您可以在我编辑时添加常见的 try catch 块。
【解决方案2】:

试试这个方法你会得到

private void makeJsonArrayRequest() {



        showpDialog();

        JsonArrayRequest req = new JsonArrayRequest( delprourl,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d("ress", response.toString());

                        // Parsing json
                        try {

                            for (int i = 0; i < response.length(); i++) {

                                JSONObject person = (JSONObject) response
                                        .get(i);

                                System.out.println("person" + person);

                                //get your id here

                        String id = person.getString("id");
                        Log.e("id: ", id);
                            }




                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                        hidepDialog();

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        //adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                hidepDialog();

            }
        });


        MyApplication.getInstance().addToReqQueue(req, "jreq");
    }


    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

【讨论】:

  • .get(i) 中有错误;但无论如何,我已经找到答案了,感谢您的帮助aditya
猜你喜欢
  • 1970-01-01
  • 2021-03-06
  • 2020-02-26
  • 2016-02-22
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多