How to convert automatically list of objects to JSONArray with Gson library in java?

This way is worked for me:

Convert all list to String.

String element = gson.toJson(
                    groupsList,
           new TypeToken<ArrayList<GroupItem>>() {}.getType());

Create JSONArray from String:

    JSONArray list = new JSONArray(element);

The org.json based classes included in Android don't have any features related to converting Java POJOs to/from JSON.

If you have a list of some class (List<GroupItem>) and you absolutely need to convert that to a org.json.JSONArray you have two choices:

A) Use Gson or Jackson to convert to JSON, then parse that JSON into a JSONArray:

List<GroupItem> list = ...
String json = new Gson().toJson(list);
JSONArray array = new JSONArray(json);

B) Write code to create the JSONArray and the JSONObjects it will contain from your Java objects:

JSONArray array = new JSONArray();
for (GroupItem gi : list)
{
    JSONObject obj = new JSONObject();
    obj.put("fieldName", gi.fieldName);
    obj.put("fieldName2", gi.fieldName2);
    array.put(obj);
}

Why do you want to use GSON to convert to an org.json class? Nor do you need to write any custom code to get a JSONArray. The org.json api provides a way to do it.

  LinkedList list = new LinkedList();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);
  JSONArray jsonArray = new JSONArray(list);
  System.out.print(jsonArray);

Tags:

Java

Json

Gson