我有一个ArrayList,可在ArrayAdapter中用于ListView。我需要将列表中的项目转换为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 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"}] 希望有一天能对某人有所帮助! 问题来源于stack overflow
如果我正确阅读了JSONArray构造函数,则可以从任何Collection生成它们(arrayList是Collection的子类),如下所示:
ArrayList list = new ArrayList (); list.add("foo"); list.add("baar"); JSONArray jsArray = new JSONArray(list);
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。