刚刚实现了JSONArrayAdapter以将JSON数据导入ListView。它扩展了android.widget.SimpleAdapter
并且与其父类非常相似。
它只有一个JSONArray
转换为用于初始化所述SimpleAdapter
一个List<Map<String, String>>
一个静态方法。
import ...
public class JSONArrayAdapter extends SimpleAdapter {
public JSONArrayAdapter(Context context, JSONArray jsonArray,
int resource, String[] from, int[] to) {
super(context, getListFromJsonArray(jsonArray), resource, from, to);
}
// method converts JSONArray to List of Maps
protected static List<Map<String, String>> getListFromJsonArray(JSONArray jsonArray) {
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map;
// fill the list
for (int i = 0; i < jsonArray.length(); i++) {
map = new HashMap<String, String>();
try {
JSONObject jo = (JSONObject) jsonArray.get(i);
// fill map
Iterator iter = jo.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, jo.getString(currentKey));
}
// add map to list
list.add(map);
} catch (JSONException e) {
Log.e("JSON", e.getLocalizedMessage());
}
}
return list;
}
}
只要使用同样的方式为内置Android适配器一样SimpleCursorAdapter用绳子(您的JSON数据的密钥)的映射整数(你的意见的ListView行)。请参阅documentation of SimpleAdapter。