Home >Java >javaTutorial >How to convert Java Array or ArrayList to JsonArray in Java using Gson?
JavaArray is an object that stores multiple variables of the same type. It saves the original type and Object references and ArrayList can represent resizable lists of objects. We can add, delete, find, sort and replace elements using lists. JsonArray can parse the text in a string to produce an object similar to a vector. We can use the toJsonTree().getAsJsonArray() method of the Gson class to convert an array or ArrayList into a JsonArray.
public JsonElement toJsonTree(java.lang.Object src)
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()); } }
{"jsonArray1":[["elem1-1","elem1-2"],["elem2-1","elem2-2"]],"jsonArray2":[["elem1-1-B","elem1-2-B"],["elem2-1-B","elem2-2-B"]]}
The above is the detailed content of How to convert Java Array or ArrayList to JsonArray in Java using Gson?. For more information, please follow other related articles on the PHP Chinese website!