Jackson - Convert Java Map Object to JSON

In this post, we will see how to convert Java Map object into JSON 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 Java Map Object to JSON

Let's demonstrates how to convert a Map Java object to JSON is using the ObjectMapper.writeValueAsString() method.

JacksonMapToJson.java

package net.javaguides.jackson;

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

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

public class JacksonMapToJson {

    public static void main(String[] args) throws JsonProcessingException {

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

        Map < String, Integer > days = new HashMap < > ();
        days.put("MON", Calendar.MONDAY);
        days.put("TUE", Calendar.TUESDAY);
        days.put("WED", Calendar.WEDNESDAY);
        days.put("THU", Calendar.THURSDAY);
        days.put("FRI", Calendar.FRIDAY);
        days.put("SAT", Calendar.SATURDAY);
        days.put("SUN", Calendar.SUNDAY);

        String json = mapper.writeValueAsString(days);
        System.out.println(json);
    }
}
Output:
{
  "THU" : 5,
  "TUE" : 3,
  "WED" : 4,
  "SAT" : 7,
  "FRI" : 6,
  "MON" : 2,
  "SUN" : 1
}

References



Comments