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

Jackson for Java. Is it more than JSON?

JSON has been a popular data-interchange format for quite some time now. It is not just simple, but also lightweight, and most programmers find it easy to use. However, JSON can be cumbersome to work with when you need more complex functionality.

That’s where Jackson for Java comes in. Jackson is a powerful JSON library that provides a wide range of features that make working with JSON much easier. In this blog post, we will discuss what Jackson for Java is, how it differs from regular JSON, and how you can use it in your own projects. We will also take a look at the pros and cons of using Jackson for Java so that you can decide if it is the right library for you.

What is Jackson for Java, and what are its Features?

Jackson is a Java library that provides a number of features that make working with JSON much easier. Some of the most notable features of Jackson for Java include:

  • The ability to annotate fields so that they are mapped to specific JSON keys: With Jackson, you can annotate fields in your Java objects so that they are mapped to specific keys in the JSON document. This makes it much easier to work with complex JSON documents. For example, if you have a field in your Java object that is mapped to a “name” key in the JSON document, you can access that field using the @JsonProperty("name") annotation.

  • Support for POJOs (Plain Old Java Objects) and JAXB beans (Java Architecture for XML Binding): Jackson supports both POJOs and JAXB beans. This means that you can serialize and deserialize objects without writing any boilerplate code.

  • A wide range of modules that provide additional functionality: Jackson comes with a number of modules that provide additional functionality. These modules include support for XML, YAML, and CSV formats.

In addition to these features, Jackson also has excellent performance thanks to its use of streaming data processing. This means that it can handle large amounts of data with ease.

JSON vs. Jackson for Java – what’s the difference?

The main difference between JSON and Jackson for Java is that Jackson is a library that provides additional functionality on top of JSON. This includes features such as the ability to annotate fields, support for POJOs and JAXB beans, and the ability to serialize and deserialize objects without writing any boilerplate code.

So, if you need additional functionality beyond what JSON provides, then Jackson is the library for you. However, if you only need the basic functionality that JSON provides, then JSON is a better choice.

How to use Jackson for Java in your Project?

If you want to use Jackson for Java in your project, the first step is to add the library to your project dependencies.

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

The easiest way to do this is using a dependency management tool such as Maven or Gradle. Once you have added the Jackson library to your project, you can start using it in your code. For example, if you have a field in your Java object that is mapped to a “name” key in the JSON document, you can access that field using the @JsonProperty("name") annotation. Here is an example of how you can convert List object to JSON. Here, we’ll be using the ObjectMapper.writeValueAsString() method.

package net.javaguides.jackson;

import java.util.ArrayList;
import java.util.List;

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

/**
* Using Jackson API for list serialization and deserialization
* @author ramesh fadatare
*
*/
public class JacksonListToJson {
    public static void main(String[] args) throws JsonProcessingException {

        // Create ObjectMapper object.
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        List < String > progLangs = new ArrayList < > ();
        progLangs.add("C");
        progLangs.add("C++");
        progLangs.add("Java");
        progLangs.add("Java EE");
        progLangs.add("Python");
        progLangs.add("Scala");
        progLangs.add("JavaScript");
        // Serialize Object to JSON.
        String json = mapper.writeValueAsString(progLangs);

        // Print json
        System.out.println(json);
    }
}

You can also use Jackson to serialize and deserialize objects without writing any boilerplate code. This is because Jackson automatically generates the necessary code for you. To do this, you simply need to add the @JsonSerialize and @JsonDeserialize annotations to your Java objects.

If you have some experience on Jackson for Java, you may want to include it in your resume. Now, a resume for a programmer should list programming languages, software, and tools the individual is proficient in. Additionally, project experience and technical skills should be highlighted. A résumé is essentially your career booster so you will need to ensure that it also showcases all your skills and experience. Take time to include every essential detail.

Pros and Cons of Using Jackson for Java

Jackson is a very powerful library that can make working with JSON much easier. There are pros and cons to using Jackson for Java. The main pro is that it’s a very fast and lightweight library, which makes it ideal for large-scale projects. It can also serialize and deserialize Java objects quickly.

However, one potential con is that it can be difficult to reverse certain operations performed by the library, such as converting back from JSON to Java. For example, if you have a Java object with a list of Cat objects, and you want to convert it back to JSON, reversing the process might not be as straightforward as you’d like. In cases like this, you may need to use a different library or write your own code to handle the conversion.

Another potential downside of using Jackson is that because it’s so popular, there may be less flexibility in how you use it. For example, if you want to use Jackson for XML parsing, you may need to use a third-party library such as JAXB.

Overall, Jackson is a very powerful library that can make working with JSON much easier. It has a few potential downsides, but its pros far outweigh its cons.

Comparison of Other Popular JSON Libraries

There are many different JSON libraries available for Java. Some of the most popular include Gson, org.json, and FastJSON. Gson is a library that can be used for converting between Java objects and JSON documents. It can also be used for serializing and deserializing objects. Gson has excellent performance thanks to its use of streaming data processing.

Org.json is a library that provides JSON parsing and generation in Java. It’s simple and easy to use, but it doesn’t provide as much functionality as some other libraries on this list. Here is an example of how to parse JSON string in Java with org.json library.

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++) {
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

See more examples on this page. FastJSON is a high-performance JSON library for Java. It’s simple to use and provides a wide range of features.

Wrapping Up

Overall, Jackson is the best choice for working with JSON in Java, thanks to its excellent performance and wide range of features. However, there are other great options available, so be sure to choose the library that’s right for your project.

How do I convert CSV to JSON string using Jackson?

In the following code snippet we will convert CSV into JSON string using Jackson JSON library. A comma-separated values is a delimited text, it uses comma to separate values. It starts with header on the first line, that will be the JSON key. Each subsequence lines is the data of the csv, which also contains several values separated by comma.

Let’s see the code how to do this in Jackson.

package org.kodejava.jackson;

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

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

public class CsvToJson {
    public static void main(String[] args) {
        // Comma delimited text created using text blocks
        String countries = """
                ISO, CODE, NAME\s
                CZE, CZ, Czech Republic\s
                DNK, DK, Denmark\s
                DJI, DJ, Djibouti\s
                DMA, DM, Dominica\s
                ECU, EC, Ecuador
                """;

        CsvSchema csvSchema = CsvSchema.emptySchema().withHeader();
        CsvMapper csvMapper = new CsvMapper();

        try {
            List<Map<?, ?>> list;
            try (MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader()
                    .forType(Map.class)
                    .with(csvSchema)
                    .readValues(countries)) {
                list = mappingIterator.readAll();
            }

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonPretty = objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(list);
            System.out.println(jsonPretty);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Here are the explanation of the code above:

  • Define a csv string, in this case we have a list of countries.
  • Create an empty schema of CsvSchema to process csv with header line.
  • Create an instance of CsvMapper, a specialized type of ObjectMapper.
  • Read and parse csv values into List<Map<?, ?>>.
  • We use the ObjectMapper create a pretty-printed JSON from the list object.

Running the code produces the following output:

[ {
  "ISO" : "CZE",
  "CODE" : " CZ",
  "NAME" : " Czech Republic "
}, {
  "ISO" : "DNK",
  "CODE" : " DK",
  "NAME" : " Denmark "
}, {
  "ISO" : "DJI",
  "CODE" : " DJ",
  "NAME" : " Djibouti "
}, {
  "ISO" : "DMA",
  "CODE" : " DM",
  "NAME" : " Dominica "
}, {
  "ISO" : "ECU",
  "CODE" : " EC",
  "NAME" : " Ecuador"
} ]

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>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-csv</artifactId>
        <version>2.15.2</version>
    </dependency>    
</dependencies>

Maven Central Maven Central 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 format LocalDate object using Jackson?

We have a Recording class which has a Java 8 java.time.LocalDate property. We need to deserialize and serialize this property from and to JSON string. To do this we can use the @JsonDeserialize and @JsonSerialize annotations to annotate the LocalDate property of the Recording class.

@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate releaseDate;

To use the annotation we need to create a class to deserialize and serialize the value. To create a deserializer class we create a class that extends StdDeserializer. The serializer class extends the StdSerializer class. Below is the definition of the LocalDateSerializer and LocalDateDeserializer class.

package org.kodejava.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateSerializer extends StdSerializer<LocalDate> {

    public LocalDateSerializer() {
        super(LocalDate.class);
    }

    @Override
    public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) throws IOException {
        generator.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
    }
}
package org.kodejava.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

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

public class LocalDateDeserializer extends StdDeserializer<LocalDate> {

    protected LocalDateDeserializer() {
        super(LocalDate.class);
    }

    @Override
    public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        return LocalDate.parse(parser.readValueAs(String.class));
    }
}

Let’s create a simple class that convert Recording object into JSON string and apply the date formatter defined in the LocalDateSerializer class.

package org.kodejava.jackson;

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

import java.time.LocalDate;
import java.time.Month;

public class RecordingToJson {
    public static void main(String[] args) {
        Recording recording = new Recording();
        recording.setId(1L);
        recording.setTitle("Twist and Shout");
        recording.setReleaseDate(LocalDate.of(1964, Month.FEBRUARY, 3));

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

The output of the code snippet above is:

JSON = {"id":1,"title":"Twist and Shout","releaseDate":"1964-02-03"}

And here is the complete definition of the Recording class.

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;

    // Getters and Setters

    @Override
    public String toString() {
        return "Recording{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", releaseDate=" + releaseDate +
                '}';
    }
}

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