首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将ArrayList<MyCustomClass>转换为JSONArray

将ArrayList<MyCustomClass>转换为JSONArray
EN

Stack Overflow用户
提问于 2011-01-30 16:34:17
回答 8查看 144.9K关注 0票数 129

我有一个在ArrayAdapter中用于ListView的ArrayList。我需要获取列表中的项,并将它们转换为JSONArray以发送到API。我到处寻找,但没有找到任何解释这可能是如何工作的东西,任何帮助都将不胜感激。

更新-解决方案

以下是我最终解决这个问题所做的事情。

ArrayList中的对象:

代码语言:javascript
复制
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;
    }
}

下面是我是如何转换它的:

代码语言:javascript
复制
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());
}

和输出:

代码语言:javascript
复制
[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]

希望有一天这能对别人有所帮助!

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4841952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档