Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In Java, a HashMap is a widely used data structure that we can use to store data in key-value pairs. On the other hand, JavaScript Object Notation (JSON) is a popular data interchange format commonly used to transmit data between a server and a web application.

In modern software development, it is common to encounter scenarios where data needs to be converted between different formats. One such scenario is converting a Map to JSON format.

In this tutorial, we’ll explore three ways to convert a Map to JSON format.

2. A Map Example and the Expected JSON Output

Let’s consider the following map example:

Map<String, String> data = new HashMap<>();
data.put("CS", "Post1");
data.put("Linux", "Post1");
data.put("Kotlin", "Post1");

The expected JSON output should be as follows:

{
  "CS": Post1,
  "Linux": Post1,
  "Kotlin": Post1
}

3. Java Map to JSON using Jackson

Jackson is one of the most popular Java libraries we can use while working with JSON. It offers powerful features for JSON parsing, generation, and data binding.

To convert a Map to JSON using Jackson, let’s include the jackson-databind dependency in our pom.xml file:

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

After including the dependency, we can define a test function to convert a Map to JSON using Jackson. Here’s an example:

String originalJsonData = "{\"CS\":\"Post1\",\"Linux\":\"Post1\",\"Kotlin\":\"Post1\"}";
@Test
public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException {
    Map<String, String> data = new HashMap();
    data.put("CS", "Post1");
    data.put("Linux", "Post1");
    data.put("Kotlin", "Post1");
    ObjectMapper objectMapper = new ObjectMapper();
    String jacksonData = objectMapper.writeValueAsString(data);
    Assertions.assertEquals(jacksonData, originalJsonData);
}

In the above code snippet, we created a HashMap object and added key-value pairs. Moreover, we used Jackson’s ObjectMapper to convert the HashMap to a JSON string and included assertions to verify the success of the conversion.

4. Java Map to JSON using Gson

Gson is another popular Java library that we can use to convert a Map to JSON and vice versa. It provides a simple and intuitive API for JSON processing.

Firstly we should include the following gson dependency in your pom.xml file:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Once we have included the Gson dependency, we can define a test function that converts a Map to JSON using Jackson:

@Test
public void given_HashMapData_whenUsingGson_thenConvertToJson() {
    Map<String, String> data = new HashMap<>();
    data.put("CS", "Post1");
    data.put("Linux", "Post1");
    data.put("Kotlin", "Post1");
    Gson gson = new Gson();
    Type typeObject = new TypeToken<HashMap>() {}.getType();
    String gsonData = gson.toJson(data, typeObject);
    Assertions.assertEquals(gsonData, originalJsonData);
}

The above code snippet represents a JUnit test method that uses the Gson library to convert a HashMap filled with key-value pairs into a JSON string and includes assertions to validate the successful conversion.

5. Java Map to JSON using JSON-Java

If we prefer a lightweight and minimalistic JSON library, we can use json since it provides a simple API for JSON manipulation.

To convert a Map to JSON using it, we need to add the org.json dependency to the pom.xml:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20240303</version>
</dependency>

After including the json dependency in our project, we can now define a test function that converts a Map to JSON:

@Test
public void given_HashMapData_whenOrgJson_thenConvertToJsonUsing() {
    Map<String, String> data = new HashMap<>();
    data.put("CS", "Post1");
    data.put("Linux", "Post1");
    data.put("Kotlin", "Post1");
    JSONObject jsonObject = new JSONObject(data);
    String orgJsonData = jsonObject.toString();
    Assertions.assertEquals(orgJsonData, originalJsonData);
}

We created a HashMap object and populated it with key-value pairs. Then we used the JSON-Java library’s JSONObject class to convert the HashMap into a JSON object.

6. Conclusion

In this article, we discussed converting a Map to JSON in Java. It allows us to represent structured data in a widely accepted format for interoperability and exchange.

As always, the code is available over on GitHub.

Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.