Java Jackson – Convert List to JSON array string Example

1. Introduction

Jackson is a well-known Java library that's widely used for processing JSON data. While it can parse JSON, Jackson can also serialize Java objects into their JSON representations. This tutorial demonstrates how to convert a Java List into a JSON array string using Jackson.

2. Example Steps

1. Add the Jackson library dependencies to your project.

2. Define a Java List that you'd like to convert to JSON.

3. Use Jackson's ObjectMapper class to serialize the Java List into a JSON array string.

4. Output the generated JSON array string to the console.

3. Convert List to JSON array string Example

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Arrays;
import java.util.List;

public class JacksonListToJsonArrayExample {

    public static void main(String[] args) {
        // Sample Java List.
        List<String> fruits = Arrays.asList("apple", "banana", "cherry");

        try {
            // Initialize ObjectMapper instance.
            ObjectMapper objectMapper = new ObjectMapper();

            // Convert Java List to JSON array string.
            String jsonArray = objectMapper.writeValueAsString(fruits);

            // Print out the JSON array string.
            System.out.println(jsonArray);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

Output:

["apple","banana","cherry"]

4. Step By Step Explanation

1. Initially, we define a Java List containing fruit names.

2. The ObjectMapper class from Jackson is then initialized. This class provides various methods that allow the serialization of Java objects into their JSON format.

3. To convert the Java List into a JSON array string, we use the writeValueAsString method of ObjectMapper. This method serializes the given Java object (in our case, a List) into its JSON string representation.

4. Lastly, the generated JSON array string is displayed on the console. The output verifies that the Java List was successfully serialized into a JSON array string.


Comments