convert ArrayList<MyCustomClass> to JSONArray

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:

  • jsonarray constructor: http://developer.android.com/reference/org/json/JSONArray.html#JSONArray%28java.util.Collection%29
  • collection: http://developer.android.com/reference/java/util/Collection.html

Use Gson library to convert ArrayList to JsonArray.

Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();

As somebody figures out that the OP wants to convert custom List to org.json.JSONArray not the com.google.gson.JsonArray,the CORRECT answer should be like this:

Gson gson = new Gson();

String listString = gson.toJson(
                    targetList,
           new TypeToken<ArrayList<targetListItem>>() {}.getType());

 JSONArray jsonArray =  new JSONArray(listString);