How To Convert Map To Json String In Java

In this current time, data has assumed an increasingly prominent role in the scheme of things. Thanks to modern technological advancements, data can be gathered and preserved in multifarious ways, including maps. Maps, or associative arrays as they are sometimes referred to, are data structures that are engineered to stockpile key-value pairs.

In the realm of the Java programming language, these arrays are put to use in diverse scenarios, ranging from the storage of configuration settings to the maintenance of database records and beyond.

It is a well-known fact that Java developers often face the challenge of converting a map to a JSON string. JSON  is a lightweight, highly versatile data exchange format that has emerged as a preferred choice for data exchange between web applications.

By converting a map to a JSON string, the data can be easily disseminated and transmitted between disparate systems. In the ensuing discourse, we shall expound on the step-by-step process of transforming a map into a JSON string using Java.

Why is converting Map To Json String In Java needed?

In the realm of modern software development, the conversion of a Map to a JSON string in Java is a task of considerable import, owing to several critical reasons:

  • Data exchange: JSON serves as a widely accepted data interchange format that finds frequent use in exchanging information between disparate applications, services, and systems. The conversion of a Map to a JSON string thereby facilitates the simple and efficient transmission and sharing of data across a diverse range of platforms and technologies.
  • Web services: Numerous web services mandate that data be communicated exclusively in JSON format, a mandate that RESTful APIs frequently enforce. As such, the conversion of a Map to a JSON string in Java permits developers to seamlessly integrate their applications with these web services, thereby allowing for more expansive use and functionality.
  • Configuration files: JSON also acts as a popular and standardized format for storing configuration settings, rendering the conversion of a Map to a JSON string a much-needed practice. As a result, developers can swiftly and conveniently store and retrieve configuration data in a format that is both standardized and easily readable.
  • Logging: When logging data in distributed systems, JSON is the format of choice for many developers. The conversion of a Map to a JSON string in Java, therefore, enables developers to log data in a standardized format, which can be effortlessly parsed and analyzed at a later time.

In summary, the conversion of a Map to a JSON string in Java is a task of significant importance in modern software development, with numerous benefits that include facilitating data exchange, web services integration, standardized configuration files, and streamlined logging procedures.

How to convert  Map To Json String In Java

Here are six different approaches to convert Map To Json String In Java with detailed solution steps, code, and output for each approach:

  1. Using JSONObject
  2. Using Gson
  3. Using Jackson
  4. Using Json-B
  5. Using Jackson with StringWriter
  6. Using JsonWriter

Note: For running the code, we need to add the jar file by following the below path.

Path: open intellij idea -> open project structure -> click on libraries -> click on “+” button and select the .jar file.

How to download jar file:

Link to download .jar file : https://mvnrepository.com/artifact/org.json/json/20140107

go to the link -> you will see “file” option. it is the 6th option in table. -> click on “jar” -> file will be downloaded.

Let’s dive in more with examples to each approach.

Approach 1: Using JSONObject

The JSONObject class is a part of the JSON-java library, which provides a simple way to convert a Map to a JSON string. Here’s how you can do it.

Pros:

  • Easy to use
  • No external dependencies required
  • Supports converting complex objects to JSON

Cons:

  • Limited functionality compared to other libraries
  • Doesn’t provide a way to customize the JSON output

Sample Code:

import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class MapToJsonUsingJSONObject {

    public static void main(String[] args) {
        // create a Map
        Map<String, String> map = new HashMap<>();
        map.put("name", "John");
        map.put("age", "30");

        // create a JSONObject and pass the map as a parameter
        JSONObject json = new JSONObject(map);

        // print the JSON string
        System.out.println(json.toString());
    }
}

Output:

{"age":"30","name":"John"}

Code Explanation:

  1. First, we create a Map and add some key-value pairs to it.
  2. Then, we create a JSONObject and pass the Map as a parameter to its constructor.
  3.  Finally, we print the JSON string using the toString() method of the JSONObject class.

Approach 2: Using Gson

Gson is a Java library that can be used to convert Java Objects into their JSON representation. Here’s how you can use it to convert a Map to a JSON string.

Pros:

  • Easy to use
  • Supports custom serialization and deserialization
  • Supports converting complex objects to JSON

Cons:

  • Requires an external dependency

Sample Code:

import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;

public class MapToJsonUsingGson {
    public static void main(String[] args) {

        // create a Map
        Map<String, String> map = new HashMap<>();
        map.put("name", "John");
        map.put("age", "30");

        // create a Gson object
        Gson gson = new Gson();

        // convert the Map to a JSON string using Gson
        String json = gson.toJson(map);

        // print the JSON string
        System.out.println(json);
    }
}

Output:

{"name":"John","age":"30"}

Code Explanation:

  1. First, we create a Map and add some key-value pairs to it.
  2. Then, we create a Gson object.
  3. Next, we use the toJson() method of the Gson class to convert the Map to a JSON string.
  4. Finally, we print the JSON string.

Approach 3: Using Jackson

Jackson is a JSON library for Java that can be used to serialize and deserialize Java objects to JSON and vice versa. Here’s how you can use it to convert a Map to a JSON string.

Pros:

  • High-performance
  • Supports custom serialization and deserialization
  • Supports converting complex objects to JSON

Cons:

  • Requires an external dependency
  • Complex configuration required for customization

Sample Code:

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

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

        // create a Map
        Map<String, String> map = new HashMap<>();
        map.put("name", "John");
        map.put("age", "30");

        // create an ObjectMapper object
        ObjectMapper objectMapper = new ObjectMapper();

        // convert the Map to a JSON string using Jackson
        String json = objectMapper.writeValueAsString(map);

        // print the JSON string
        System.out.println(json);
    }
}

Output:

{"name":"John","age":"30"}

Code Explanation:

  1. First, we create a Map and add some key-value pairs to it.
  2. Then, we create an ObjectMapper object from the Jackson library.
  3. We use the writeValueAsString() method of the ObjectMapper class to convert the Map to a JSON string.
  4. Finally, we print the JSON string.

Approach 4: Using Json-B

Json-B is a Java API for JSON binding, which provides a way to convert Java objects to and from JSON. Here’s how you can use it to convert a Map to a JSON string.

Pros:

  • Supports custom serialization and deserialization
  • Supports converting complex objects to JSON
  • Part of the Java EE standard

Cons:

  • Requires an external dependency for standalone Java applications

Sample Code:

import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;
import java.util.HashMap;
import java.util.Map;

public class MapToJsonUsingJsonB {

    public static void main(String[] args) {

        // create a Map
        Map<String, String> map = new HashMap<>();
        map.put("name", "John");
        map.put("age", "30");

        // create a Jsonb object
        Jsonb jsonb = JsonbBuilder.create();

        // convert the Map to a JSON string using Json-B
        String json = jsonb.toJson(map);

        // print the JSON string
        System.out.println(json);
    }
}

Output:

{"age":"30","name":"John"}

Code Explanation:

  1. First, we create a Map and add some key-value pairs to it.
  2. Then, we create a Jsonb object.
  3. Next, we use the toJson() method of the Jsonb class to convert the Map to a JSON string.
  4. Finally, we print the JSON string.

Approach 5: Using Jackson with StringWriter

In this approach, we use Jackson to convert the Map to a JSON string and write it to a StringWriter object. Here’s how you can do it.

Pros:

  • Can be used in scenarios where you need to write JSON to a stream or file instead of a string

Cons:

  • Requires an external dependency
  •  Can be less efficient than other approaches

Sample Code:

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class MapToJsonUsingJacksonWithStringWriter {
    public static void main(String[] args) throws IOException {
        // create a Map
        Map<String, String> map = new HashMap<>();
        map.put("name", "John");
        map.put("age", "30");

        // create an ObjectMapper object
        ObjectMapper mapper = new ObjectMapper();

        // create a StringWriter object
        StringWriter stringWriter = new StringWriter();

        // create a JsonGenerator object
        JsonGenerator jsonGenerator = new JsonFactory().createGenerator(stringWriter);

        // write the Map to the StringWriter using Jackson
        mapper.writeValue(jsonGenerator, map);

        // get the JSON string from the StringWriter
        String json = stringWriter.toString();

        // print the JSON string
        System.out.println(json);
    }
}    

Output:

{"name":"John","age":"30"}

Code Explanation:

  1. First, we create a Map and add some key-value pairs to it.
  2. Then, we create an ObjectMapper object.
  3. Next, we create a StringWriter object and a JsonGenerator object using the JsonFactory class.
  4. We use the writeValue() method of the ObjectMapper class to write the Map to the JsonGenerator object.
  5. Finally, we get the JSON string from the StringWriter object and print it.

Approach 6: Using JsonWriter

In this approach, we use the JsonWriter class from the JSON package in Java to write the Map to a JSON string. Here’s how you can do it:

Pros:

  • Does not require an external dependency
  • Provides fine-grained control over the output

Cons:

  • Can be more verbose than other approaches
  • Requires more low-level coding

Sample Code:

import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.json.Json;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonGeneratorFactory;

public class MapToJsonUsingJsonWriter {

    public static void main(String[] args) {

        // create a Map
        Map<String, String> map = new HashMap<>();
        map.put("name", "John");
        map.put("age", "30");

        // create a StringWriter object
        Writer stringWriter = new StringWriter();

        // create a JsonGeneratorFactory object
        JsonGeneratorFactory factory = Json.createGeneratorFactory(null);

        // create a JsonGenerator object
        JsonGenerator jsonGenerator = factory.createGenerator(stringWriter);

        // write the Map to the StringWriter using JsonWriter
        jsonGenerator.writeStartObject();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            jsonGenerator.write(entry.getKey(), entry.getValue());
        }
        jsonGenerator.writeEnd();

        // close the JsonGenerator to flush any buffered output
        jsonGenerator.close();

        // get the JSON string from the StringWriter
        String json = stringWriter.toString();

        // print the JSON string
        System.out.println(json);
    }
} 

Output:

{"name":"John","age":"30"}

 Code explanation:

  1. First, we create a Map and add some key-value pairs to it.
  2. Then, we create a StringWriter object.
  3. Next, we create a JsonGeneratorFactory object using the Json class.
  4. We use the createGenerator() method of the JsonGeneratorFactory class to create a JsonGenerator object.
  5. We use the writeStartObject() and writeEnd() methods to start and end the JSON object respectively.
  6. Inside the object, we use the write() method of the JsonGenerator class to write each key-value pair from the Map.
  7. Finally, we get the JSON string from the StringWriter object and print it.

Best Approach To Convert Map To Json String In Java

The utilization of JSONObject is unequivocally advocated for the management and manipulation of JSON data structures in the Java programming language. This methodology affords a multitude of advantageous benefits, encompassing but not restricted to:

  1. Ease of use: The JSONObject technique streamlines the convoluted process of creating, reading, and modifying JSON objects in Java, facilitating the facile handling of JSON data.
  2. Flexibility: The JSONObject approach endows the ability to formulate JSON objects with sundry structures, thereby rendering it plausible to handle intricate data structures with ease.
  3. Error handling: The technique encompasses built-in error handling capabilities, which function to preclude issues that could ensue from erroneous data or misuse of the API.
  4. Customizability: The technique confers the liberty to personalize the JSON objects generated, making it feasible to tailor them to specific requisites or needs.
  5. Integration with other Java libraries: The JSONObject approach can be effortlessly incorporated with other Java libraries, thereby fortifying the functionality and performance of the code.

All in all, the utilization of JSONObject is universally acclaimed as one of the superlative methods for working with JSON data structures in Java, on account of its facile handling, flexibility, error handling capabilities, customizability, and seamless integration with other Java libraries.

Sample Problems To Convert Map To Json String In Java

Sample Problem 1

Scenario: You are building a weather app and need to convert a Map of weather data into a JSON string to send it to a mobile app.

Sample Problem: You have a Map containing the current weather conditions for a city, including the temperature, humidity, and wind speed. You need to convert this Map into a JSON string so that it can be sent to the mobile app.

Solution steps:

  1. Create a new JSONObject.
  2. Iterate over the Map entries and add them to the JSONObject.
  3. Call the toString() method of the JSONObject to get the JSON string.

Solution Code:

import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Map containing weather data
        Map<String, Object> weatherData = new HashMap<>();
        weatherData.put("temperature", 25);
        weatherData.put("humidity", 60);
        weatherData.put("wind_speed", 10);

        // Create a new JSONObject
        JSONObject jsonObject = new JSONObject();

        // Iterate over the Map entries and add them to the JSONObject
        for (Map.Entry<String, Object> entry : weatherData.entrySet()) {
            jsonObject.put(entry.getKey(), entry.getValue());
        }

        // Get the JSON string
        String jsonString = jsonObject.toString();
        System.out.println(jsonString);
    }
}

Output:

{"temperature":25,"humidity":60,"wind_speed":10}

Sample Problem 2

Scenario: You are building an e-commerce website and need to convert a Map of product data into a JSON string to send it to a client-side JavaScript app.

Sample problem: You have a Map containing the details of a product, including its name, price, and description. You need to convert this Map into a JSON string using Gson so that it can be sent to the client-side JavaScript app.

Solution steps:

  1. Create a new Gson object.
  2. Call the toJson() method of the Gson object, passing in the Map as a parameter.

Solution Code:

import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Map containing product data
        Map<String, Object> productData = new HashMap<>();
        productData.put("name", "iPhone 13");
        productData.put("price", 999.00);
        productData.put("description", "The latest iPhone with advanced features");

        // Create a new Gson object
        Gson gson = new Gson();

        // Convert the Map to a JSON string
        String jsonString = gson.toJson(productData);
        System.out.println(jsonString);
    }
}

Output:

{"name":"iPhone 13","price":999.0,"description":"The latest iPhone with advanced features"}

Sample Problem 3

Scenario: You are building a messaging app and need to convert a Map of message data into a JSON string to send it over a network.

Sample problem: You have a Map containing the details of a message, including its sender, recipient, timestamp, and content. You need to convert this Map into a JSON string using Jackson so that it can be sent over a network.

Solution steps:

  1. Create a new ObjectMapper object.
  2. Call the writeValueAsString() method of the ObjectMapper object, passing in the Map as a parameter.

Solution Code:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        // Map containing message data
        Map<String, Object> messageData = new HashMap<>();
        messageData.put("sender", "Alice");
        messageData.put("recipient", "Bob");
        messageData.put("timestamp", "2022-03-23T14:30:00");
        messageData.put("content", "Hello, how are you?");

        // Create a new ObjectMapper object
        ObjectMapper mapper = new ObjectMapper();

        // Convert the Map to a JSON string
        String jsonString = mapper.writeValueAsString(messageData);
        System.out.println(jsonString);
    }
}

Output:

{"sender":"Alice","recipient":"Bob","timestamp":"2022-03-23T14:30:00","content":"Hello, how are you?"}

Sample Problem 4

Scenario: You are building a finance app and need to convert a Map of transaction data into a JSON string to store it in a database.

Sample problem: You have a Map containing the details of a transaction, including its ID, date, amount, and description. You need to convert this Map into a JSON string using Json-B so that it can be stored in a database.

Solution steps:

  1. Create a new Jsonb object.
  2. Call the toJson() method of the Jsonb object, passing in the Map as a parameter.

Solution Code:

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Map containing transaction data
        Map<String, Object> transactionData = new HashMap<>();
        transactionData.put("id", 1001);
        transactionData.put("date", "2022-03-23");
        transactionData.put("amount", 500.00);
        transactionData.put("description", "Purchase of groceries");

        // Create a new Jsonb object
        Jsonb jsonb = JsonbBuilder.create();

        // Convert the Map to a JSON string
        String jsonString = jsonb.toJson(transactionData);
        System.out.println(jsonString);
    }
}

Output:

{"id":1001,"date":"2022-03-23","amount":500.0,"description":"Purchase of groceries"}

Sample Problem 5

Scenario: You are building a social media app and need to convert a Map of user profile data into a JSON string to display it on a web page.

Sample problem: You have a Map containing the details of a user profile, including their name, email, date of birth, and bio. You need to convert this Map into a JSON string using Jackson and write it to a StringWriter so that it can be displayed on a web page.

Solution steps:

  1. Create a new ObjectMapper object.
  2. Create a new StringWriter object.
  3. Call the writeValue() method of the ObjectMapper object, passing in the StringWriter and the Map as parameters.
  4. Get the JSON string from the StringWriter.

Solution Code:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws IOException {
        // Map containing user profile data
        Map<String, Object> userProfileData = new HashMap<>();
        userProfileData.put("name", "John Doe");
        userProfileData.put("email", "[email protected]");
        userProfileData.put("dateOfBirth", "1990-01-01");
        userProfileData.put("bio", "I'm a software developer.");

        // Create a new ObjectMapper object
        ObjectMapper mapper = new ObjectMapper();

        // Create a new StringWriter object
        StringWriter writer = new StringWriter();

        // Convert the Map to a JSON string and write it to the StringWriter
        mapper.writeValue(writer, userProfileData);

        // Get the JSON string from the StringWriter
        String jsonString = writer.toString();
        System.out.println(jsonString);
    }
}

Output:

{"name":"John Doe","email":"[email protected]","dateOfBirth":"1990-01-01","bio":"I'm a software developer."}

Sample Problem 6

Scenario: You are building a weather app and need to convert a Map of weather data into a JSON string to display it in a mobile app.

Sample problem: You have a Map containing the details of the current weather, including the temperature, humidity, wind speed, and description. You need to convert this Map into a JSON string using JsonWriter so that it can be displayed in a mobile app.

Solution steps:

  1. Create a new StringWriter object.
  2. Create a new JsonWriter object, passing in the StringWriter as a parameter.
  3. Call the beginObject() method of the JsonWriter object.
  4. Loop through the entries of the Map and call the name() and value() methods of the JsonWriter object for each key-value pair.
  5. Call the endObject() method of the JsonWriter object.
  6. Get the JSON string from the StringWriter.

Solution Code:

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.stream.JsonWriter;

public class Main {
    public static void main(String[] args) {
        // Map containing weather data
        Map<String, Object> weatherData = new HashMap<>();
        weatherData.put("temperature", 20.5);
        weatherData.put("humidity", 60);
        weatherData.put("windSpeed", 10);
        weatherData.put("description", "Partly cloudy");

        // Create a new StringWriter object
        StringWriter writer = new StringWriter();

        // Create a new JsonWriter object, passing in the StringWriter as a parameter
        JsonWriter jsonWriter = new JsonWriter(writer);

        try {
            // Start the JSON object
            jsonWriter.beginObject();

            // Loop through the entries of the Map and add them to the JSON object
            for (Map.Entry<String, Object> entry : weatherData.entrySet()) {
                jsonWriter.name(entry.getKey()).value(entry.getValue().toString());
            }

            // End the JSON object
            jsonWriter.endObject();

            // Get the JSON string from the StringWriter
            String jsonString = writer.toString();
            System.out.println(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

{"temperature":20.5,"humidity":60,"windSpeed":10,"description":"Partly cloudy"}

Conclusion

In conclusion, converting a Map to a JSON string in Java can be achieved using various approaches, each with its own unique features and benefits. Among the most popular methods are using JSONObject, Gson, Jackson, Json-B, Jackson with StringWriter, and JsonWriter.

If simplicity and flexibility are important, JSONObject can be a suitable choice. Gson offers a convenient way of customizing the JSON format, while Jackson provides faster processing and better memory efficiency. For seamless integration with other Java libraries, Json-B may be a good option.

The approach using Jackson with StringWriter is useful for producing pretty-printed JSON output. Finally, if performance is a top priority, JsonWriter can provide better speed and memory usage than other methods.

Choosing the most appropriate approach depends on the needs and requirements. It is recommended to consider the advantages and limitations of each method before selecting them. Regardless of the chosen approach, converting Map to JSON string in Java is a valuable skill for any Java developer working with JSON data.