convert ArrayList<MyCustomClass> to JSONArray

pmko picture pmko · Jan 30, 2011 · Viewed 130.6k times · Source

I have an ArrayList that I use within an ArrayAdapter for a ListView. I need to take the items in the list and convert them to a JSONArray to send to an API. I've searched around, but haven't found anything that explains how this might work, any help would be appreciated.

UPDATE - SOLUTION

Here is what I ended up doing to solve the issue.

Object in 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;
    }
}

Here is how I converted it:

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());
}

And the output:

[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]

Hope this helps someone some day!

Answer

Nanne picture Nanne · Jan 30, 2011

If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:

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

References: