Android JSONArray到ArrayList

我试图在我的Android应用程序中解析JSONArray和ArrayList。 PHP脚本正确地返回预期的结果,但是Java在resultsList.add(map)失败并出现空指针exception

 public void agencySearch(String tsearch) { // Setting the URL for the Search by Town String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php"; // Building parameters for the search List params = new ArrayList(); params.add(new BasicNameValuePair("City", tsearch)); // Getting JSON string from URL JSONArray json = jParser.getJSONFromUrl(url_search_agency, params); for (int i = 0; i < json.length(); i++) { HashMap map = new HashMap(); try { JSONObject c = (JSONObject) json.get(i); //Fill map Iterator iter = c.keys(); while(iter.hasNext()) { String currentKey = (String) iter.next(); map.put(currentKey, c.getString(currentKey)); } resultsList.add(map); } catch (JSONException e) { e.printStackTrace(); } }; MainActivity.setResultsList(resultsList); } 

试试这样可以帮到你,

 public void agencySearch(String tsearch) { // Setting the URL for the Search by Town String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php"; // Building parameters for the search List params = new ArrayList(); params.add(new BasicNameValuePair("City", tsearch)); // Getting JSON string from URL JSONArray json = jParser.getJSONFromUrl(url_search_agency, params); ArrayList> resultsList = new ArrayList>(); for (int i = 0; i < json.length(); i++) { HashMap map = new HashMap(); try { JSONObject c = json.getJSONObject(position); //Fill map Iterator iter = c.keys(); while(iter.hasNext()) { String currentKey = it.next(); map.put(currentKey, c.getString(currentKey)); } resultsList.add(map); } catch (JSONException e) { e.printStackTrace(); } }; MainActivity.setResultsList(resultsList); } 

使用自定义方法将JSONArray转换为List而不是迭代和构建List。

怎么称呼:

 try { ArrayList> list = (ArrayList>) toList(json); } catch (JSONException e) { e.printStackTrace(); } 

将json数组转换为List:

 private List toList(JSONArray array) throws JSONException { List list = new ArrayList(); int size = array.length(); for (int i = 0; i < size; i++) { list.add(fromJson(array.get(i))); } return list; } 

将json转换为Object:

 private Object fromJson(Object json) throws JSONException { if (json == JSONObject.NULL) { return null; } else if (json instanceof JSONObject) { return jsonToMap((JSONObject) json); } else if (json instanceof JSONArray) { return toList((JSONArray) json); } else { return json; } } 

将json转换为map:

 public Map jsonToMap(JSONObject object) throws JSONException { Map map = new HashMap(); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); map.put(key, fromJson(object.get(key)).toString()); } return map; }