Home > Java > javaTutorial > body text

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

王林
Release: 2023-09-08 12:57:02
forward
1531 people have browsed it

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.

Syntax
public JsonElement toJsonTree(java.lang.Object src)
Copy after login

Example

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());
   }
}
Copy after login

Output

{"jsonArray1":[["elem1-1","elem1-2"],["elem2-1","elem2-2"]],"jsonArray2":[["elem1-1-B","elem1-2-B"],["elem2-1-B","elem2-2-B"]]}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!