开发者社区> 问答> 正文

将ArrayList <MyCustomClass>转换为JSONArray

我有一个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

展开
收起
保持可爱mmm 2020-02-08 10:32:09 400 0
1 条回答
写回答
取消 提交回答
  • 如果我正确阅读了JSONArray构造函数,则可以从任何Collection生成它们(arrayList是Collection的子类),如下所示:

    ArrayList list = new ArrayList (); list.add("foo"); list.add("baar"); JSONArray jsArray = new JSONArray(list);

    2020-02-08 10:33:04
    赞同 展开评论 打赏
问答分类:
API
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载