Node返回无数组名JSON数组时,Android Volley适配替代方案问询
从无外层数组名的JSON中加载数据到Android Spinner
我的JSON结果
这是我的JSON输出,此处没有数组名称
[{"item":"WATER"},{"item":"DFG"},{"item":"2InchPipe"},{"item":"5InchPipe"}]
需求场景
我希望在Android Spinner中显示这些item,原本使用Volley方法从JSON获取所有item。
最开始我写的Volley请求代码是这样的:
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext()); StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { 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);
遇到的问题
这里我卡壳了,就是下面这行代码不知道该怎么写——因为返回的JSON本身就是一个数组,没有外层的键名:
JSONArray jsonArray=jsonObject.getJSONArray("*What to do here*");
最终解决方法
后来我换了Volley的JsonArrayRequest直接处理数组类型的响应,问题就解决了:
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 );
说白了就是:原来用StringRequest去处理数组JSON,还要先转成JSONObject再找数组,这步完全错了——因为返回的根本不是对象,直接就是数组。改用JsonArrayRequest可以直接拿到JSONArray对象,遍历里面的每个JSONObject取出item字段就可以了。
内容的提问来源于stack exchange,提问作者Shabek Mahmood
相关产品推荐
相关产品推荐

