Java Jackson – Convert Map to JSON array string Example

1. Introduction

Jackson is a popular Java library used for processing JSON data. In addition to parsing JSON, Jackson can also serialize Java objects into JSON representations. This guide will illustrate how to convert a Java Map into a JSON array string using Jackson.

2. Program Steps

1. Ensure Jackson library dependencies are included in your project.

2. Create a Java Map you want to convert to JSON.

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

4. Display the generated JSON array string.

3. Code Program

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

import java.util.HashMap;
import java.util.Map;

public class JacksonMapToJsonArrayExample {

    public static void main(String[] args) {
        // Sample Java Map.
        Map<String, String> fruitColors = new HashMap<>();
        fruitColors.put("apple", "red");
        fruitColors.put("banana", "yellow");
        fruitColors.put("cherry", "dark red");

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

            // Convert Java Map to JSON array string.
            String jsonArray = objectMapper.writeValueAsString(fruitColors.entrySet().toArray());

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

Output:

[{"apple":"red"},{"banana":"yellow"},{"cherry":"dark red"}]

4. Step By Step Explanation

1. We first create a Java Map containing fruit names as keys and their colors as values.

2. The ObjectMapper class from Jackson is initialized. This class offers methods for serializing Java objects into JSON format.

3. For converting the Java Map into a JSON array string, we first transform the Map entries into an array using the entrySet().toArray() method. Then, using the writeValueAsString method of ObjectMapper, we serialize the array into a JSON string.

4. Finally, the generated JSON array string is printed to the console. This output confirms that the Java Map was correctly serialized into a JSON array string.


Comments