Convert Map to JSON array string in Java

1. Overview

In modern Java applications, especially with RESTful web services, there's often a requirement to convert Java objects into JSON format and vice versa. When representing data structures like a list of users in a user management system, converting a Map to a JSON array string becomes handy. In this guide, we'll explore how Jackson, a widely used Java library, can facilitate this conversion.

Check out all the Java Jackson JSON tutorials and examples: 50+ Java Jackson JSON Tutorials with Examples

2. Development Steps

1. Set up a new Maven project.

2. Incorporate the necessary Jackson dependencies.

3. Construct a sample Map representing a list of users.

4. Use Jackson's ObjectMapper to transform this Map into a JSON array string.

5. Output the resulting JSON array string.

3. Create a Maven Project

There are different ways to create a simple Maven project:

Create a Simple Maven Project using the Command Line Interface

Create a Simple Maven Project using  Eclipse IDE

Create a Simple Maven Project using  IntelliJ IDEA

4. Maven Dependencies

Open the pom.xml file, and add the following Jackson data binding dependency:

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

5. Example 1 - Convert Map to JSON array string in Java

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class MainApp {
    public static void main(String[] args) {
        // Create a sample Map representing users
        Map<String, String> user1 = new HashMap<>();
        user1.put("id", "1");
        user1.put("name", "John Doe");
        Map<String, String> user2 = new HashMap<>();
        user2.put("id", "2");
        user2.put("name", "Jane Smith");
        Map<String, Map<String, String>> users = new HashMap<>();
        users.put("user1", user1);
        users.put("user2", user2);
        // Create an ObjectMapper instance
        ObjectMapper mapper = new ObjectMapper();
        try {
            // Convert Map to JSON array string
            String jsonArrayString = mapper.writeValueAsString(users);
            // Display the JSON array string
            System.out.println(jsonArrayString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

{"user1":{"id":"1","name":"John Doe"},"user2":{"id":"2","name":"Jane Smith"}}

Code Explanation:

1. We start by creating a sample Map containing two users.

2. We initialize an instance of ObjectMapper, a pivotal component of Jackson.

3. Utilizing the writeValueAsString() function of the ObjectMapper, we convert the Map into a JSON array string.

4. The result is printed out, showing a JSON representation of our initial Map.

6. Example 2 - Convert Map to JSON array string in Java

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;
public class MapToJsonExample {
    public static void main(String[] args) {
        try {
            // Example of complex Map
            Map<String, Object> john = new HashMap<>();
            john.put("name", "John");
            john.put("age", 30);
            john.put("address", Map.of("street", "123 Main St", "city", "Springfield", "zipcode", "12345"));
            john.put("phoneNumbers", Arrays.asList("123-456-7890", "987-654-3210"));
            Map<String, Object> jane = new HashMap<>();
            jane.put("name", "Jane");
            jane.put("age", 25);
            jane.put("address", Map.of("street", "456 Elm St", "city", "Shelbyville", "zipcode", "54321"));
            jane.put("phoneNumbers", Arrays.asList("111-222-3333", "444-555-6666"));
            // Putting these maps in a List to represent a JSON array
            List<Map<String, Object>> listOfPeople = Arrays.asList(john, jane);
            // Create ObjectMapper instance
            ObjectMapper objectMapper = new ObjectMapper();
            // Convert List of Maps to JSON array string
            String jsonString = objectMapper.writeValueAsString(listOfPeople);
            // Print the JSON array string
            System.out.println(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

[{"name":"John","age":30,"address":{"zipcode":"12345","street":"123 Main St","city":"Springfield"},"phoneNumbers":["123-456-7890","987-654-3210"]},{"name":"Jane","age":25,"address":{"zipcode":"54321","street":"456 Elm St","city":"Shelbyville"},"phoneNumbers":["111-222-3333","444-555-6666"]}]

7. Conclusion

Jackson provides a robust and effective way to convert Java Maps into JSON array strings. This proves to be especially useful when you need to convey complex data structures like a user list in a structured, universally-accepted format like JSON. By leveraging Jackson, Java developers can seamlessly interface with various systems and services that communicate via JSON.

Check out all the Java Jackson JSON tutorials and examples: 50+ Java Jackson JSON Tutorials with Examples

Comments