Java Jackson – Convert JSON string to Map

1. Introduction

Jackson is a popular Java library designed for processing JSON data. One of its powerful capabilities is the ability to convert JSON structures into Java Maps, making the parsed data easy to navigate and manipulate. This article provides an example of how to achieve this.

2. Example Steps

1. Ensure Jackson dependencies are included in your project.

2. Create a sample JSON string with key-value pairs.

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

4. Iterate and display the parsed data in the Map.

3. Convert JSON string to Map using Jackson

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

import java.util.Map;

public class JacksonJsonToMapExample {

    public static void main(String[] args) {
        // Sample JSON string with key-value pairs.
        String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        try {
            // Instantiate ObjectMapper.
            ObjectMapper objectMapper = new ObjectMapper();

            // Convert the JSON string into a Map.
            Map<String, Object> resultMap = objectMapper.readValue(json, Map.class);

            // Display the key-value pairs from the Map.
            for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

Output:

name: John
age: 30
city: New York

4. Step By Step Explanation

1. First, we set up a sample JSON string that contains some basic key-value pairs.

2. We then use the ObjectMapper class from Jackson, which is a mainstay for data binding between Java objects and JSON.

3. The readValue method of ObjectMapper is called to transform the JSON string into a Java Map. The resultant Map will have Strings as keys and Objects as values, allowing for varied data types in the JSON.

4. Once the data is in the Map, it's straightforward to iterate over its entries and display the key-value pairs.

5. The displayed output confirms the successful parsing and conversion of the JSON string into the Java Map structure.


Comments