Jackson - Convert JSON to Java Map

In this post, we will see how to convert JSON string to Java Map object using the Jackson library.

Dependencies

Let’s first add the following dependencies to the pom.xml:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
This dependency will also transitively add the following libraries to the classpath:
  • jackson-annotations-2.9.8.jar
  • jackson-core-2.9.8.jar
  • jackson-databind-2.9.8.jar
Always use the latest versions on the Maven central repository for Jackson databind.

Jackson - Convert JSON to Java Map

We can use the ObjectMapper.readValue() method for converting a JSON text to a Map object.
The following example demonstrates how to convert the JSON text to Map.

JacksonJsonToMap.java

package net.javaguides.jackson;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonJsonToMap {
    public static void main(String[] args) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        String json = "{" +
            "  \"THU\" : 5," +
            "  \"TUE\" : 3," +
            "  \"WED\" : 4," +
            "  \"SAT\" : 7," +
            "  \"FRI\" : 6," +
            "  \"MON\" : 2," +
            "  \"SUN\" : 1" +
            "}";

        @SuppressWarnings("unchecked")
        Map < String, Integer > days = mapper.readValue(json, Map.class);

        for (Entry < String, Integer > day: days.entrySet()) {
            System.out.println(day.getKey() + "=" + day.getValue());
        }
    }
}
Output:
THU=5
TUE=3
WED=4
SAT=7
FRI=6
MON=2
SUN=1

References

Comments