Convert JSON Array to List: Gson, Jackson and Org.json

When working with JSON data, it’s often required to convert JSON arrays into Java lists/arraylists to work with the data more efficiently. This Java article explores how to accomplish this using three popular Java libraries:

1. Setup

This article reads the data.json file from the project’s /resources directory, which contains the JSON array. The file content is:

[
  {"id":1,"name":"Alex","age":41},
  {"id":2,"name":"Brian","age":42},
  {"id":3,"name":"Charles","age":43}
]

We read the file content into Java String using the following code:

URL fileUrl = JsonArrayToList.class.getClassLoader().getResource("data.json");
Path filePath = Paths.get(fileUrl.toURI());
String jsonArray = Files.readString(filePath);

We will read the JSON content into a List of Person objects.

@Data
@NoArgsConstructor
@AllArgsConstructor
class Person {

  long id;
  String name;
  int age;
}

2. Using Jackson

Jackson is a popular Java library for working with JSON and XML data. It is automatically included in Spring framework, so the technique used here can be used in Spring application also.

To convert a JSON array into a Java list using Jackson, follow these steps:

2.1. Maven

Add the latest version of Jackson library, if it is not in the project runtime.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.15.2</version>
</dependency>

2.2. Convert JSON Array to List

When we use Jackson to parse JSON data into Java objects or lists, we should know the target type when dealing with generic types like List<T> or Map<K, V>. The TypeReference class provides the necessary type information to Jackson at runtime when deserializing JSON data into generic types.

List<Person> readPersonListFromJsonArray(String jsonArray) throws JsonProcessingException {

  //Use autowired bean in Spring / Spring Boot
  ObjectMapper objectMapper = new ObjectMapper();
  TypeReference<List<Person>> jacksonTypeReference = new TypeReference<>() {};
  List<Person> personList = objectMapper.readValue(jsonArray, jacksonTypeReference);
  return personList;
}

3. Using Gson

Gson, developed by Google, is also a widely used Java library for working with JSON data. Gson provides a simple and convenient API to serialize Java objects to JSON and deserialize JSON into Java objects.

For converting a JSON array into a Java List using Gson, follow these steps:

3.1. Maven

Add the latest version of Gson library, if it is not in the project runtime.

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.10.1</version>
</dependency>

3.2. Convert JSON Array to List

Just like TypeReference is used by Jackson, Gson uses TypeToken, which helps to deserialize JSON data into complex generic types.

In Java, due to type erasure, the generic type information of collections (like List<T>) is not available at runtime. So Gson doesn’t know the exact type we want to deserialize to when dealing with generic types. The TypeToken class retains this information and acts as a workaround for the limitations of type erasure.

List<Person> readPersonListFromJsonArray(String jsonArray) {

  //Use autowired bean in Spring / Spring Boot
  Gson gson = new Gson();
  Type listType = new TypeToken<List<Person>>() {}.getType();
  List<Person> personList = gson.fromJson(jsonArray, listType);
  return personList;
}

4. Using Org.json

Org.json or JSON-Java is a simple and lightweight Java-based library that we can use to encode or decode between JSON and XML, HTTP headers, Cookies, and CDL. It is fully compliant with JSON Specification (RFC-4627).

For converting a JSON array into a Java List using Org.json, follow these steps:

4.1. Maven

Add the latest version of org.json library, if it is not in the project runtime.

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20230618</version>
</dependency>

4.2. Convert JSON Array to List

The following code parses a JSON array containing person data and converts it into a list of Java Person objects using the JSONArray and JSONObject classes.

  • JSONArray represents the array of person objects in the JSON.
  • JSONObject represents a person object in the JSON.
List<Person> readPersonListFromJsonArray(String json) {

  JSONArray jsonArray = new JSONArray(json);
  List<Person> personList = new ArrayList<>();

  for (int i = 0; i < jsonArray.length(); i++) {

    JSONObject jsonPerson = jsonArray.getJSONObject(i);

    long id = jsonPerson.getLong("id");
    String name = jsonPerson.getString("name");
    int age = jsonPerson.getInt("age");

    Person person = new Person(id, name, age);
    personList.add(person);
  }
  return personList;
}

5. Conclusion

In this article, we explored how to use Gson, Jackson, and Org.json libraries for converting a JSON array into a Java list. Each library has its strengths and is suitable for different scenarios. Gson provides a straightforward and easy-to-use API, Jackson offers high performance and flexibility, and Org.json is a more lightweight option.

We should the library that best fits our project’s requirements and leverages its capabilities. For example, in Spring applications, Jackson is included by default, so it makes sense to use it.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.