我有一个在 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"}]
希望有一天这对某人有所帮助!
最佳答案
如果我正确阅读了 JSONArray 构造函数,您可以像这样从任何 Collection(arrayList 是 Collection 的子类)构建它们:
ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);
引用资料:
关于android - 将 ArrayList<MyCustomClass> 转换为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4841952/
相关文章:
javascript - JSON 和 JavaScript 对象有什么区别?
python - UnicodeDecodeError : 'utf8' codec can't d
json - 如何使用标准 Scala 类在 Scala 中解析 JSON?
javascript - 是否有任何可公开访问的 JSON 数据源来测试真实世界的数据?
javascript - 使用 JQuery 定义要追加的 HTML 模板
javascript - 向 JSON 对象添加新的数组元素