JSONObject is a very popular in terms of transferring data between two systems. Now a days everything is transferred between the systems is JSONObject.
It’s been long time I’ve been playing with JSONObject, JSONArray and more. In this tutorial we will go over steps on how to convert Java ArrayList to JSONObject.
We will use Google GSON utility for the same. Just include below dependencies to your Java Enterprise project and you should be good.
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.4</version> </dependency>
As per today, version 2.8.4
is the latest version. Please update to latest version if you could.
In our Java Program, we will create ArrayList first and then will convert it to JSONObject.
Let’s get started:
- Create Java Class CrunchifyArrayListToJsonObject.java
- Create ArrayList named crunchify
- Add 6 companyNames to ArrayList
- Print ArrayList
- Convert it to JSONObject/JSONArray using Google JSON
- Print JSONObject
Here is a complete code:
package crunchify.com.tutorial; import java.util.ArrayList; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * @author Crunchify.com * Program: Best way to convert Java ArrayList to JSONObject * Version: 1.0.0 * */ public class CrunchifyArrayListToJsonObject { public static void main(String a[]) { ArrayList<String> crunchify = new ArrayList<String>(); crunchify.add("Google"); crunchify.add("Facebook"); crunchify.add("Crunchify"); crunchify.add("Twitter"); crunchify.add("Snapchat"); crunchify.add("Microsoft"); log("Raw ArrayList ===> " + crunchify); // Use this builder to construct a Gson instance when you need to set configuration options other than the default. GsonBuilder gsonBuilder = new GsonBuilder(); // This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. // Gson instances are Thread-safe so you can reuse them freely across multiple threads. Gson gson = gsonBuilder.create(); String JSONObject = gson.toJson(crunchify); log("\nConverted JSONObject ==> " + JSONObject); Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); String prettyJson = prettyGson.toJson(crunchify); log("\nPretty JSONObject ==> " + prettyJson); } private static void log(Object print) { System.out.println(print); } }
Eclipse console output:
Raw ArrayList ===> [Google, Facebook, Crunchify, Twitter, Snapchat, Microsoft] Converted JSONObject ==> ["Google","Facebook","Crunchify","Twitter","Snapchat","Microsoft"] Pretty JSONObject ==> [ "Google", "Facebook", "Crunchify", "Twitter", "Snapchat", "Microsoft" ]
I hope you can use this simple utility to convert any Java Objects to JSONObject or JSONArray.