How do I convert Map to JSON and vice versa using Jackson?

In the following code snippet we will convert java.util.Map object into JSON string and convert back the JSON string into Java Map object. In this example we will be using the Jackson library.

To convert from Map to JSON string the steps are:

  • Create a map of string keys and values.
  • Create an instance of Jackson ObjectMapper.
  • To convert map to JSON string we call the writeValueAsString() method and pass the map as argument.
// Converting Map to JSON
String json = null;
try {
    json = mapper.writeValueAsString(colours);
    System.out.println("json = " + json);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

Now, to convert from JSON string back to map we can do it in the following steps:

  • Create a JSON string, in this case we use the one converted from the colours map.
  • Create an instance of Jackson ObjectMapper.
  • Call the mapper’s readValue() method with JSON string and an empty instance of TypeReference as arguments.
// Converting JSON to MAP
try {
    Map<String, String> newColours =
            mapper.readValue(json, new TypeReference<>() {});
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

And here is the complete code snippet.

package org.kodejava.jackson;

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

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

public class MapToJson {
    public static void main(String[] args) {
        Map<String, String> colours = new HashMap<>();
        colours.put("BLACK", "#000000");
        colours.put("RED", "#FF0000");
        colours.put("GREEN", "#008000");
        colours.put("BLUE", "#0000FF");
        colours.put("YELLOW", "#FFFF00");
        colours.put("WHITE", "#FFFFFF");

        ObjectMapper mapper = new ObjectMapper();

        // Converting Map to JSON
        String json = null;
        try {
            json = mapper.writeValueAsString(colours);
            System.out.println("json = " + json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        // Converting JSON to MAP
        try {
            Map<String, String> newColours =
                    mapper.readValue(json, new TypeReference<>() {});
            System.out.println("Map:");
            for (var entry : newColours.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

Running the code snippet above will print the following output:

json = {"RED":"#FF0000","WHITE":"#FFFFFF","BLUE":"#0000FF","BLACK":"#000000","YELLOW":"#FFFF00","GREEN":"#008000"}
Map:
RED = #FF0000
WHITE = #FFFFFF
BLUE = #0000FF
BLACK = #000000
YELLOW = #FFFF00
GREEN = #008000

Maven Dependencies

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

Maven Central Maven Central

How to pretty print JSON string using Jackson?

The following example demonstrates how to pretty print the JSON string produces by Jackson library. To produce well formatted JSON string we create the ObjectMapper instance and enable the SerializationFeature.INDENT_OUTPUT feature. To enable this feature we need to call the enable() method of the ObjectMapper and provide the feature to be enabled.

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(recording);
System.out.println(json);

On the second example below we format unformatted JSON string. To do this we use the ObjectMapper‘s readValue(String, Class<T>) method which accept the JSON string and Object.class as the value type. The readValue() method return an Object. To format the JSON object we call mapper.writerWithDefaultPrettyPrinter().writeValueAsString(Object). This will produce a pretty formatted JSON.

ObjectMapper mapper = new ObjectMapper();
Object jsonObject = mapper.readValue(json, Object.class);
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
System.out.println(prettyJson);

Below is the complete code snippets.

package org.kodejava.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.kodejava.jackson.support.Artist;
import org.kodejava.jackson.support.Label;
import org.kodejava.jackson.support.Recording;

import java.io.IOException;
import java.time.LocalDate;
import java.time.Month;

public class JsonIndentOutput {
    public static void main(String[] args) {
        JsonIndentOutput.formatObjectToJsonString();
        JsonIndentOutput.formatJsonString();
    }

    private static void formatObjectToJsonString() {
        Recording recording = new Recording();
        recording.setId(1L);
        recording.setTitle("Yellow Submarine");
        recording.setReleaseDate(LocalDate.of(1969, Month.JANUARY, 17));
        recording.setArtist(new Artist(1L, "The Beatles"));
        recording.setLabel(new Label(1L, "Apple"));

        ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
        try {
            String json = mapper.writeValueAsString(recording);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    private static void formatJsonString() {
        String json = """
                {"id":1,"title":"Yellow Submarine","releaseDate":"1969-01-17","artist":{"id":1,"name":"The Beatles"},"label":{"id":1,"name":"Apple"}}
                """;
        ObjectMapper mapper = new ObjectMapper();
        try {
            Object jsonObject = mapper.readValue(json, Object.class);
            String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
            System.out.println(prettyJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The code snippet above will pretty print the following JSON string:

{
  "id" : 1,
  "title" : "Yellow Submarine",
  "releaseDate" : "1969-01-17",
  "artist" : {
    "id" : 1,
    "name" : "The Beatles"
  },
  "label" : {
    "id" : 1,
    "name" : "Apple"
  }
}

Here are the structure of Recording, Artist and Label classes.

package org.kodejava.jackson.support;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.kodejava.jackson.LocalDateDeserializer;
import org.kodejava.jackson.LocalDateSerializer;

import java.time.LocalDate;

public class Recording {
    private Long id;
    private String title;

    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate releaseDate;
    private Artist artist;
    private Label label;

    // Getters and Setters
}
package org.kodejava.jackson.support;

public class Artist {
    private Long id;
    private String name;

    public Artist() {
    }

    public Artist(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getters and Setters
}
package org.kodejava.jackson.support;

public class Label {
    private Long id;
    private String title;

    public Label(Long id, String title) {
        this.id = id;
        this.title = title;
    }

    // Getters and Setters
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How to read and write Java object to JSON file?

The following example demonstrate how to serialize and deserialize Java object to JSON file. The Jackson’s ObjectMapper class provides writeValue(File, Object) and readValue(File, Class<T>) methods which allow us to write an object into JSON file and read JSON file into an object respectively.

package org.kodejava.jackson;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.kodejava.jackson.support.Artist;

import java.io.File;
import java.io.IOException;

public class ObjectToJsonFile {
    public static void main(String[] args) {
        Artist artist = new Artist();
        artist.setId(1L);
        artist.setName("The Beatles");

        ObjectMapper mapper = new ObjectMapper();

        File file = new File("artist.json");
        try {
            // Serialize Java object info JSON file.
            mapper.writeValue(file, artist);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Deserialize JSON file into Java object.
            Artist newArtist = mapper.readValue(file, Artist.class);
            System.out.println("newArtist.getId() = " + newArtist.getId());
            System.out.println("newArtist.getName() = " + newArtist.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The result of the code snippet are:

newArtist.getId() = 1
newArtist.getName() = The Beatles

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How to convert JSON string to Java object?

In the following example we will convert JSON string to Java object using ObjectMapper class from the Jackson library. This class provides a method readValue(String, Class<T>) which will deserialize a JSON string into Java object. The first argument to the method is the JSON string and the second parameter is the result type of the conversion.

In the code below you will see:

  • Define a JSON string, here we have the id and name keys.
  • Create a Jackson ObjectMapper which maps JSON string to POJO.
  • Map the json string into an Artist object by calling the readValue() method.
  • Read the value of artist object properties.
package org.kodejava.jackson;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.kodejava.jackson.support.Artist;

import java.io.IOException;

public class JsonToObject {
    public static void main(String[] args) {
        String json = """
                {
                    "id": 1,
                    "name": "The Beatles"
                }
                """;

        ObjectMapper mapper = new ObjectMapper();
        try {
            Artist artist = mapper.readValue(json, Artist.class);
            System.out.println("Artist = " + artist);

            System.out.println("artist.getId() = " + artist.getId());
            System.out.println("artist.getName() = " + artist.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

And here is the definition of Artist class.

package org.kodejava.jackson.support;

public class Artist {
    private Long id;
    private String name;

    public Artist() {
    }

    public Artist(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getters & Setters

    @Override
    public String toString() {
        return "Artist{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

The code snippet above will print to following output:

Artist = Artist{id=1, name='The Beatles'}
artist.getId() = 1
artist.getName() = The Beatles

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How to convert Java object to JSON string?

The following example shows how to convert Java object into JSON string using Jackson. Jackson provide ObjectMapper class provides functionality to read and write JSON data. The writeValueAsString(Object) method to serialize any Java object into string.

Here are the steps to convert POJOs into JSON string:

  • Create a Java object, set some properties on it.
  • Creates a Jackson ObjectMapper that can read and write JSON, either to and from POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model.
  • Convert the Artist object artist into JSON by calling the writeValueAsString().
  • Print the json string.
package org.kodejava.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.kodejava.jackson.support.Artist;

public class ObjectToJson {
    public static void main(String[] args) {
        Artist artist = new Artist();
        artist.setId(1L);
        artist.setName("The Beatles");

        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(artist);
            System.out.println("JSON = " + json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

Running the code snippet above will print out the following result:

JSON = {"id":1,"name":"The Beatles"}

And here is the definition of Artist class.

package org.kodejava.jackson.support;

public class Artist {
    private Long id;
    private String name;

    public Artist() {
    }

    public Artist(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getters & Setters

    @Override
    public String toString() {
        return "Artist{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central