【发布时间】:2011-06-18 00:52:43
【问题描述】:
我有一个在 ArrayAdapter 中用于 ListView 的 ArrayList。我需要获取列表中的项目并将它们转换为 JSONArray 以发送到 API。我四处搜索,但没有找到任何解释这可能如何工作的东西,任何帮助将不胜感激。
更新 - 解决方案
这是我最终解决问题的方法。
ArrayList 中的对象:
public class ListItem {
private long _masterId;
private String _name;
private long _category;
public ListItem(long masterId, String name, long category) {
_masterId = masterId;
_name = name;
_category = category;
}
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Id", _masterId);
obj.put("Name", _name);
obj.put("Category", _category);
} catch (JSONException e) {
trace("DefaultListItem.toString JSONException: "+e.getMessage());
}
return obj;
}
}
我是这样转换的:
ArrayList<ListItem> myCustomList = .... // list filled with objects
JSONArray jsonArray = new JSONArray();
for (int i=0; i < myCustomList.size(); i++) {
jsonArray.put(myCustomList.get(i).getJSONObject());
}
还有输出:
[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]
希望有一天这对某人有所帮助!
【问题讨论】:
标签: android json arraylist arrays jsonobject