Convert JSON Array to List of Long Type in Java

In this guide, you will learn how to convert a JSON Array into a List of Long values using the Gson library in Java.

First, install Gson library in your project.

For Maven:


For Gradle:

implementation group: '', name: 'gson', version: '2.10.1'

This code snippet demonstrates how to convert a JSON array into a List of Long values in Java:

import java.util.List;
import java.lang.reflect.Type;

public class Example {

   public static void main(String[] args) {
      // Json array data
      String jsonArrayExampleData = "[\"123\",\"456\",\"456\",\"232\"]";

      // creating an object of Gson
      Gson gson = new Gson();

      // Converting to List of Long type
      Type type = new TypeToken>() {}.getType();
      List list = gson.fromJson(jsonArrayExampleData, type);



The output of the above code is as follows:

[123, 456, 456, 232]

Here, in this example, the Example class contains the main method, where the JSON array data that we want to convert is defined as a string: String jsonArrayExampleData = "[\"123\",\"456\",\"456\",\"232\"]";.

In the main method, an instance of the Gson class is created: Gson gson = new Gson();. Gson is a Java library that provides methods for converting Java objects to JSON and vice versa. To convert the JSON array to a List of Long values, a Type object is defined using the TypeToken class: Type type = new TypeToken>() {}.getType();. This captures the generic type information of List. Next, the fromJson() method of the Gson object is used to parse the JSON array data and convert it into a List of Long values. The fromJson() method takes two arguments: the JSON array string and the Type object representing the desired target type. The resulting List of Long values is assigned to the list variable: List list = gson.fromJson(jsonArrayExampleData, type);. Finally, the list is printed to the console using System.out.println(list);.