How to convert Java array or ArrayList to JsonArray

How to convert Java array or ArrayList to JsonArray - Hello friend inabnomaniiyaha, In the article that you read this time with the title How to convert Java array or ArrayList to JsonArray, we have prepared this article well for you to read and take information in it. hopefully the contents of the post Artikel Code-java-example,what we write you can understand. Alright, happy reading.

Judul : How to convert Java array or ArrayList to JsonArray
link : How to convert Java array or ArrayList to JsonArray

Baca juga


How to convert Java array or ArrayList to JsonArray

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

 Syntax

public JsonElement toJsonTree(java.lang.Object src)

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

   }

}

Output

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



That's the articleHow to convert Java array or ArrayList to JsonArray

That's it for the article How to convert Java array or ArrayList to JsonArray this time, hopefully can be useful for all of you. well, see you in another article post.

You are now reading the articleHow to convert Java array or ArrayList to JsonArray with link addresshttps://inabnonapudyawanabing.blogspot.com/2021/05/how-to-convert-java-array-or-arraylist.html

0 Response to "How to convert Java array or ArrayList to JsonArray"

Post a Comment

Tips Tricks for Android Phone

Tips & Tricks for Android Phone is a free android app and Collection of Tips and Tricks related to using your android mobile device lik...