Convert from JSONArray to ArrayList<CustomObject> - Android

stanete picture stanete · Feb 23, 2014 · Viewed 52.3k times · Source

I converted an ArrayList to an JSONArray. How can I convert it back?

The final result must be an ArrayList. Thank you in advance.

EDIT:

This is how I convert the ArrayList to JSONArray:

String string_object= new Gson().toJson(MyArrayList<OBJECT>);
JSONArray myjsonarray = new JSONArray(string_object);

Answer

Purushotham picture Purushotham · Feb 24, 2014

You can convert your JsonArray or json string to ArrayList<OBJECT> using Gson library as below

ArrayList<OBJECT> yourArray = new Gson().fromJson(jsonString, new TypeToken<List<OBJECT>>(){}.getType());

//or

ArrayList<OBJECT> yourArray = new Gson().fromJson(myjsonarray.toString(), new TypeToken<List<OBJECT>>(){}.getType());

Also while converting your ArrayList<OBJECT> to JsonArray, no need to convert it to string and back to JsonArray

 JsonArray myjsonarray = new Gson().toJsonTree(MyArrayList<OBJECT>).getAsJsonArray();

Refer Gson API documentation for more details. Hope this will be helpful.