How to Create JSONArray for a List<Class name>

Using Gson Library it will be very simple.

From JSON String to ArrayList of Object as:

Type listType = 
     new TypeToken<ArrayList<Student>>(){}.getType();
ArrayList<Student> yourClassList = new Gson().fromJson(jsonArray, listType);

And to Json from Array List of Object as:

ArrayList<Student> sampleList = new ArrayList<Student>();
String json = new Gson().toJson(sampleList);

The Gson Library is more simple to use than JSONObject and JSONArray implementation.


You will have to include the jettison jar in you project and import the required classes.

JSONObject jObject = new JSONObject();
try
{
    JSONArray jArray = new JSONArray();
    for (Student student : sudentList)
    {
         JSONObject studentJSON = new JSONObject();
         studentJSON.put("name", student.getName());
         studentJSON.put("age", student.getAge());
         jArray.put(studentJSON);
    }
    jObject.put("StudentList", jArray);
} catch (JSONException jse) {
    jse.printStacktrace();
}

Create JSONArray like below.

JSONArray jsArray = new JSONArray(arrayList);