我有一个ArrayList,我在ListView的ArrayAdapter中使用。 我需要将列表中的项目转换为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;
Here is how I converted it:
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"}]