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:
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);