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.


Let’s first add the following dependencies to the pom.xml:
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.


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();

        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);
  "THU" : 5,
  "TUE" : 3,
  "WED" : 4,
  "SAT" : 7,
  "FRI" : 6,
  "MON" : 2,
  "SUN" : 1