Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In modern software development, the exchange of data between different systems is a common requirement. One popular data interchange format is JSON (JavaScript Object Notation).

Besides, Java is a widely used programming language that provides libraries and frameworks that facilitate working with JSON data. One common task is converting a Java List to a JSON array.

In this tutorial, we’ll explore different approaches to achieve this conversion, providing us with practical examples and insights.

2. Overview

The main purpose of JSON is to serialize and transmit structured data over network connections. Since it serves as a convenient format for transmitting data between a server and web applications.

Furthermore, web services and APIs often rely on JSON format to provide public data in a standardized manner. Its versatility makes it compatible with modern programming languages, allowing seamless integration across different platforms and technologies.

In this scenario, let’s consider a Java list named “articles” that contains elements as follows:

public List<String> list = Arrays.asList("Article 1", "Article 2", "Article 3");
public String expectedJsonArray = "[\"Article 1\",\"Article 2\",\"Article 3\"]";

We aim to convert this “articles” list into a JSON array. So, the expected output should be as follows:

[
   "Article 1",
   "Article 2",
   "Article 3"
]

We’ll explore three different approaches in the following sections to accomplish the conversion task.

2. Conversion Using Gson

Gson is a popular Java library developed by Google for working with JSON data since it provides a simple API for converting Java objects to JSON.

First of all, we need to add the Gson dependency to the pom.xml file:

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

Now, we’ll use the Gson library to convert the Java List to a JSON array. Here’s a test method:

@Test
public void given_JavaList_whenUsingGsonLibrary_thenOutJsonArray() {
    Gson gson = new Gson();
    String jsonArray = gson.toJson(list);
    Assert.assertEquals(expectedJsonArray, jsonArray);
}

In the above test method, we create a Gson instance (gson) and then use the toJson() method to convert the articles List to a JSON array represented as a string.

Finally, we utilize the Assert class to verify the equality of the output jsonArray and the expectedJsonArray. This ensures that the conversion of the Java List to a JSON array has been performed correctly and matches the expected result.

3. Conversion Using Jackson

If we are seeking to use a powerful and flexible API, Jackson simplifies the task of converting Java objects to JSON and vice versa.

To use Jackson, let’s first add the following dependency to the pom.xml file:

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

After adding the required dependency, we’ll use the ObjectMapper class from Jackson to convert the Java List to a JSON array as follows:

@Test
public void given_JavaList_whenUsingJacksonLibrary_thenOutJsonArray() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    String jsonArray = objectMapper.writeValueAsString(list);
    Assert.assertEquals(expectedJsonArray, jsonArray);
}

In the provided code snippet, we instantiate the ObjectMapper class and utilize its writeValueAsString() method. This method allows us to convert the articles List into a JSON array, which is then represented as a string.

4. Conversion Using org.json

In addition to external libraries like Gson and Jackson, Java also provides a built-in library called org.json for JSON processing. To convert a Java List to a JSON array using org.json, we can use the JSONArray class to accomplish this task. Here’s an example:

@Test
public void given_JavaList_whenOrgJsonLibrary_thenOutJsonAray() {
    JSONArray jsonArray = new JSONArray(list);
    Assert.assertEquals(expectedJsonArray, jsonArray.toString());
}

In the above code snippet, we create an instance of the JSONArray class, passing the articles List as a parameter. The JSONArray class provides a toString() method to obtain the JSON array as a string representation.

5. Conclusion

In this article, we discussed converting a Java List to a JSON array as a common task in modern software development. We explored three different approaches using popular libraries like Gson, Jackson, and org.json to complete this task.

As usual, the code samples are available on GitHub.

Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.