How to convert Java array or ArrayList to JsonArray using Gson in Java?

The Java Arrays are objects which store multiple variables of the same type, it holds primitive types and object references and an ArrayList can represent a resizable list of objects. We can add, remove, find, sort and replace elements using the list. A JsonArray can parse text from a string to produce a vector-like object. We can convert an array or ArrayList to JsonArray using the toJsonTree().getAsJsonArray() method of Gson class.


public JsonElement toJsonTree(java.lang.Object src)


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



Updated on: 08-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started