如果节点响应没有json数组名

时间:2018-05-20 10:53:58

标签: android json android-spinner

我的JSON结果

  

这是我的JSON输出。这里的数组名称不可用

[{"item":"WATER"},{"item":"DFG"},{"item":"2InchPipe"},{"item":"5InchPipe"}]

Android代码

  

但我想在android微调器中显示该项目。我用volley方法从JSON获取所有项目。

 RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
    StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
           String getitem=
            try{
                JSONObject jsonObject=new JSONObject(response);

                    JSONArray jsonArray=jsonObject.getJSONArray("*What to do here*");
                    for(int i=0;i<jsonArray.length();i++){
                        JSONObject jsonObject1=jsonArray.getJSONObject(i);
                        String country=jsonObject1.getString("Item");
                        CountryName.add(country);
                    }

                spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
            }catch (JSONException e){e.printStackTrace();}
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    int socketTimeout = 30000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(policy);
    requestQueue.add(stringRequest);

我对这一行有疑问

JSONArray jsonArray=jsonObject.getJSONArray("*What to do here*");

最后我使用以下代码获得了解决方案

  JsonArrayRequest requestQueue = new JsonArrayRequest(URL,
  new Response.Listener<JSONArray>() {
  @Override
  public void onResponse(JSONArray response) {         
  for (int i = 0; i < response.length(); i++) {
  try {
  JSONObject obj = response.getJSONObject(i);
  String country = obj.getString("item");
  CountryName.add(country);
  spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, 
  android.R.layout.simple_spinner_dropdown_item, CountryName));
  }
  catch (JSONException e) {
  e.printStackTrace();
  }
  }
  }
  }, new Response.ErrorListener() {
  @Override
  public void onErrorResponse(VolleyError error) {
  }
  });     
  }
   MySingleton.getmInstance(MainActivity.this).addToRequestQue(requestQueue );

1 个答案:

答案 0 :(得分:0)

您可以直接在Array中传递输出:

JSONArray jsonArray=new JSONArray (response);
 for(int i=0;i<jsonArray.length();i++){
                    JSONObject jsonObject1=jsonArray.getJSONObject(i);
                    String country=jsonObject1.getString("Item");
                    CountryName.add(country);
                }