1. Introduction
JSON (JavaScript Object Notation) is a widely used data interchange format. In Java, we often need to convert JSON to a List for easier manipulation and traversal. The Gson library from Google is a great library for handling JSON in Java. In this blog post, we will use the Gson library to convert a JSON array to a List of elements.
2. Program Steps
1. Add the Gson library to the project.
2. Create a JSON array String.
3. Create a Gson object.
4. Use the fromJson() method of the Gson object to convert the JSON array to a List.
5. Print the resulting List to the console.
3. Code Program
// Importing necessary classes
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
public class JsonToList {
public static void main(String[] args) {
// Step 2: Create a JSON array String
String jsonArray = "[\"Apple\", \"Banana\", \"Cherry\"]";
// Step 3: Create a Gson object
Gson gson = new Gson();
// Step 4: Define the Type for the List and use the fromJson() method to convert the JSON array to List
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> fruits = gson.fromJson(jsonArray, listType);
// Step 5: Print the resulting List to the console
System.out.println(fruits);
}
}
Output:
[Apple, Banana, Cherry]
4. Step By Step Explanation
Step 1: Ensure the Gson library is added to your project, as it's not part of the standard Java library. This can be done using build tools like Maven or Gradle.
Step 2: A JSON array String jsonArray is created containing elements "Apple", "Banana", and "Cherry".
Step 3: A Gson object is created to invoke the methods required for conversion.
Step 4: The Type for the List is defined using TypeToken. The fromJson() method of the Gson object is then used to convert the jsonArray to a List of Strings, which is stored in the variable fruits.
Step 5: Finally, the fruits List is printed to the console, displaying the elements that were in the JSON array.
This example illustrates the convenience and utility of using the Gson library to convert a JSON array to a List in Java.