Below code should work for your case.

List<Customer> customerList = CustomerDB.selectAll();

Gson gson = new Gson();
JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<Customer>>() {}.getType());

if (! element.isJsonArray() ) {
// fail appropriately
    throw new SomeException();
}

JsonArray jsonArray = element.getAsJsonArray();

Heck, use List interface to collect values before converting it JSON Tree.

Answer from Ahsan Mahboob Shah on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-java-array-or-arraylist-to-jsonarray-using-gson-in-java
How to convert Java array or ArrayList to JsonArray using Gson in Java?
import com.google.gson.*; import java.util.*; public class JavaArrayToJsonArrayTest { public static void main(String args[]) { String[][] strArray = {{"elem1-1", "elem1-2"}, {"elem2-1", "elem2-2"}}; ArrayList<ArrayList<String>> arrayList = new ArrayList<>(); for(int i = 0; i < strArray.length; i++) { ArrayList<String> nextElement = new ArrayList<>(); for(int j = 0; j < strArray[i].length; j++) { nextElement.add(strArray[i][j] + "-B"); } arrayList.add(nextElement); } JsonObject jsonObj = new JsonObject(); // array to JsonArray JsonArray jsonArray1 = new Gson().toJsonTree(strArray).getAsJsonArray(); // ArrayList to JsonArray JsonArray jsonArray2 = new Gson().toJsonTree(arrayList).getAsJsonArray(); jsonObj.add("jsonArray1", jsonArray1); jsonObj.add("jsonArray2", jsonArray2); System.out.println(jsonObj.toString()); } }
Top answer
1 of 6
321

Definitely the easiest way to do that is using Gson's default parsing function fromJson().

There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).

In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();

List<String> yourList = new Gson().fromJson(yourJson, listType);

In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.

You may want to take a look at Gson API documentation.

2 of 6
19

Below code is using com.google.gson.JsonArray. I have printed the number of element in list as well as the elements in List

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class Test {

    static String str = "{ "+ 
            "\"client\":\"127.0.0.1\"," + 
            "\"servers\":[" + 
            "    \"8.8.8.8\"," + 
            "    \"8.8.4.4\"," + 
            "    \"156.154.70.1\"," + 
            "    \"156.154.71.1\" " + 
            "    ]" + 
            "}";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {

            JsonParser jsonParser = new JsonParser();
            JsonObject jo = (JsonObject)jsonParser.parse(str);
            JsonArray jsonArr = jo.getAsJsonArray("servers");
            //jsonArr.
            Gson googleJson = new Gson();
            ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
            System.out.println("List size is : "+jsonObjList.size());
                    System.out.println("List Elements are  : "+jsonObjList.toString());


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

OUTPUT

List size is : 4

List Elements are  : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
🌐
HowToDoInJava
howtodoinjava.com › home › gson › gson – parse json array to java array or list
Gson - Parse JSON Array to Java Array or List
April 4, 2023 - Java has both – arrays and lists. To parse JSON, with array as root, we can use the following method syntax. Here ArrayItem is the class type of data elements in the array. ArrayItem[] userArray = new Gson().fromJson(jsonSource, ArrayItem[].class);
🌐
GitHub
gist.github.com › 21ec4a3a1fe9dc52e2cd195479428f98
JAVA array or ArrayList to JsonArray (Gson) · GitHub
JAVA array or ArrayList to JsonArray (Gson). GitHub Gist: instantly share code, notes, and snippets.
🌐
Tabnine
tabnine.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray.getAsJsonArray java code examples | Tabnine
public static List<Object> ... + " \"CAD\": 78,\n" + " \"CHF\": 54600.78,\n" + " \"USD\": 20735.52\n" + " }}"; Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(json, JsonObject.class); JsonObject supplyPrice ...
🌐
Futurestud.io
futurestud.io › tutorials › gson-mapping-of-arrays-and-lists-of-objects
Gson — Mapping of Arrays and Lists of Objects - Future Studio
June 2, 2016 - Similar to nested objects, we don't have a direct value for menu. Instead, JSON declares that a list of objects is coming by wrapping the value with []. As mentioned above, there is no difference if this is an array or a list. In the JSON data structure it looks identical. The content of the menu are a bunch of objects. In our case, they're the restaurant's menu items. Let's run Gson to see how a complete JSON would look like.
Find elsewhere
Top answer
1 of 2
88

Here's a comprehensive example on how to use Gson with a list of objects. This should demonstrate exactly how to convert to/from Json, how to reference lists, etc.

Test.java:

import com.google.gson.Gson;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;


public class Test {

  public static void main (String[] args) {

    // Initialize a list of type DataObject
    List<DataObject> objList = new ArrayList<DataObject>();
    objList.add(new DataObject(0, "zero"));
    objList.add(new DataObject(1, "one"));
    objList.add(new DataObject(2, "two"));

    // Convert the object to a JSON string
    String json = new Gson().toJson(objList);
    System.out.println(json);

    // Now convert the JSON string back to your java object
    Type type = new TypeToken<List<DataObject>>(){}.getType();
    List<DataObject> inpList = new Gson().fromJson(json, type);
    for (int i=0;i<inpList.size();i++) {
      DataObject x = inpList.get(i);
      System.out.println(x);
    }

  }


  private static class DataObject {
    private int a;
    private String b;

    public DataObject(int a, String b) {
      this.a = a;
      this.b = b;
    }

    public String toString() {
      return "a = " +a+ ", b = " +b;
    }
  }

}

To compile it:

javac -cp "gson-2.1.jar:." Test.java

And finally to run it:

java -cp "gson-2.1.jar:." Test

Note that if you're using Windows, you'll have to switch : with ; in the previous two commands.

After you run it, you should see the following output:

[{"a":0,"b":"zero"},{"a":1,"b":"one"},{"a":2,"b":"two"}]
a = 0, b = zero
a = 1, b = one
a = 2, b = two

Keep in mind that this is only a command line program to demonstrate how it works, but the same principles apply within the Android environment (referencing jar libs, etc.)

2 of 2
0

My version of gson list deserialization using a helper class:

public List<E> getList(Class<E> type, JSONArray json) throws Exception {
    Gson gsonB = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    return gsonB.fromJson(json.toString(), new JsonListHelper<E>(type));
}



public class JsonListHelper<T> implements ParameterizedType {

  private Class<?> wrapped;

  public JsonListHelper(Class<T> wrapped) {
    this.wrapped = wrapped;
  }

  public Type[] getActualTypeArguments() {
    return new Type[] {wrapped};
  }

  public Type getRawType() {
    return List.class;
  }

  public Type getOwnerType() {
    return null;
  }

}

Usage

List<Object> objects = getList(Object.class, myJsonArray);
🌐
Javadoc.io
javadoc.io › doc › com.google.code.gson › gson › 2.8.5 › com › google › gson › JsonArray.html
JsonArray - gson 2.8.5 javadoc
Bookmarks · Latest version of com.google.code.gson:gson · https://javadoc.io/doc/com.google.code.gson/gson · Current version 2.8.5 · https://javadoc.io/doc/com.google.code.gson/gson/2.8.5 · package-list path (used for javadoc generation -link option) · https://javadoc.io/doc/com.goog...
🌐
Attacomsian
attacomsian.com › blog › gson-convert-json-array-to-from-java-list
Convert JSON Array to List using Gson in Java
October 14, 2022 - In this quick tutorial, you'll learn how to use the Gson library to convert a JSON array string into a list of Java Objects and vice versa.
🌐
Crunchify
crunchify.com › json tutorials › how to use gson -> fromjson() to convert the specified json into an object of the specified class
How to use Gson -> fromJson() to convert the specified JSON into an Object of the Specified Class • Crunchify
February 16, 2023 - https://crunchify.com/wp-content/uploads/code/crunchify-gson.txt · Please download and put it under C: drive or Documents folder and update path below. package crunchify.com.tutorials; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; import com.google.gson.Gson; /** * @author Crunchify.com * Gson() -> fromJson() to deserializes the specified Json into an object of the specified class */ public class CrunchifyGoogleGSONExample { public static void main(String[] args) { JSONArray array = readFileContent(
🌐
Javadoc.io
javadoc.io › doc › com.google.code.gson › gson › 2.6.2 › com › google › gson › JsonArray.html
JsonArray - gson 2.6.2 javadoc
Bookmarks · Latest version of com.google.code.gson:gson · https://javadoc.io/doc/com.google.code.gson/gson · Current version 2.6.2 · https://javadoc.io/doc/com.google.code.gson/gson/2.6.2 · package-list path (used for javadoc generation -link option) · https://javadoc.io/doc/com.goog...
🌐
Baeldung
baeldung.com › home › java › java list › converting a java list to a json array
Converting a Java List to a Json Array | Baeldung
June 18, 2025 - In the above test method, we create a Gson instance (gson) and then use the toJson() method to convert the articles List to a JSON array represented as a string. Finally, we utilize the Assert class to verify the equality of the output jsonArray ...
🌐
Level Up Lunch
leveluplunch.com › java › examples › convert-json-array-to-arraylist-gson
Json array to ArrayList gson | Level Up Lunch
August 10, 2014 - You will notice that we have commented out the ability to print json in a pretty format. Finally calling the toJson will serialize the navigation object into its equivalent Json representation.
🌐
Baeldung
baeldung.com › home › java › java list › serializing and deserializing a list with gson
Serializing and Deserializing a List with Gson | Baeldung
February 19, 2026 - In order to deserialize the list, we’ll have to provide a custom deserializer: public class AnimalDeserializer implements JsonDeserializer<Animal> { private String animalTypeElementName; private Gson gson; private Map<String, Class<? extends Animal>> animalTypeRegistry; public AnimalDeserializer(String animalTypeElementName) { this.animalTypeElementName = animalTypeElementName; this.gson = new Gson(); this.animalTypeRegistry = new HashMap<>(); } public void registerBarnType(String animalTypeName, Class<? extends Animal> animalType) { animalTypeRegistry.put(animalTypeName, animalType); } publ
🌐
Rip Tutorial
riptutorial.com › jsonarray to java list (gson library)
Java Language Tutorial => JsonArray to Java List (Gson Library)
Now pass the JsonArray 'list' to the following method which returns a corresponding Java ArrayList: public ArrayList<String> getListString(String jsonList){ Type listType = new TypeToken<List<String>>() {}.getType(); //make sure the name 'list' ...