转换ArrayList 到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<ListItem> myCustomList = .... // list filled with objectsJSONArray 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);
参考文献:
- jsonarray构造函数:http : //developer.android.com/reference/org/json/JSONArray.html#JSONArray%28java.util.Collection%29
- 集合:http: //developer.android.com/reference/java/util/Collection.html
以上是 转换ArrayList 到JSONArray 的全部内容, 来源链接: utcz.com/qa/413083.html








