You can also try something like this with Gson Library:

package com.stackoverflow.works;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/*
 * @Author: sarath_sivan
 */

public class MapToJsonConverter {

    /*
     * @Description: Method to convert Map to JSON String
     * @param: map Map<String, String> 
     * @return: json String
     */
    public static String convert(Map<String, String> map) {
        Gson gson = new Gson();
        String json = gson.toJson(map);
        return json;
    }

    /*
     * @Description: Method to convert JSON String to Map
     * @param: json String 
     * @return: map Map<String, String> 
     */
    public static Map<String, String> revert(String json) {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> map = gson.fromJson(json, type);
        return map;
    }

    /*
     * @Description: Method to print elements in the Map
     * @param: map Map<String, String> 
     * @return: void 
     */
    public static void printMap(Map<String, String> map) {
        for (String key : map.keySet()) {
            System.out.println("map.get(\"" + key + "\") = " + map.get(key));
        }
    }

    /*
     * @Description: Method to print the JSON String
     * @param: json String 
     * @return: void 
     */
    public static void printJson(String json) {
        System.out.println("json = " + json);
    }

    /*
     * @Description: Main method to test the JSON-MAP convert/revert logic
     */
    public static void main(String[] args) {
        Map<String, String> paymentCards = new HashMap<String, String>();
        paymentCards.put("card_switch", "Master");
        paymentCards.put("issuing_bank", "ICCI");
        paymentCards.put("card_Type", "DebitCard");

        String json = convert(paymentCards); //converting Map to JSON String
        System.out.println("Map to JSON String");
        System.out.println("******************");
        printJson(json); 

        System.out.println();

        paymentCards = revert(json); //converting JSON String to Map
        System.out.println("JSON String to Map");
        System.out.println("******************");
        printMap(paymentCards);
    }

}

The output look like this:

Answer from 1218985 on Stack Overflow
Top answer
1 of 4
18

You can also try something like this with Gson Library:

package com.stackoverflow.works;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/*
 * @Author: sarath_sivan
 */

public class MapToJsonConverter {

    /*
     * @Description: Method to convert Map to JSON String
     * @param: map Map<String, String> 
     * @return: json String
     */
    public static String convert(Map<String, String> map) {
        Gson gson = new Gson();
        String json = gson.toJson(map);
        return json;
    }

    /*
     * @Description: Method to convert JSON String to Map
     * @param: json String 
     * @return: map Map<String, String> 
     */
    public static Map<String, String> revert(String json) {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> map = gson.fromJson(json, type);
        return map;
    }

    /*
     * @Description: Method to print elements in the Map
     * @param: map Map<String, String> 
     * @return: void 
     */
    public static void printMap(Map<String, String> map) {
        for (String key : map.keySet()) {
            System.out.println("map.get(\"" + key + "\") = " + map.get(key));
        }
    }

    /*
     * @Description: Method to print the JSON String
     * @param: json String 
     * @return: void 
     */
    public static void printJson(String json) {
        System.out.println("json = " + json);
    }

    /*
     * @Description: Main method to test the JSON-MAP convert/revert logic
     */
    public static void main(String[] args) {
        Map<String, String> paymentCards = new HashMap<String, String>();
        paymentCards.put("card_switch", "Master");
        paymentCards.put("issuing_bank", "ICCI");
        paymentCards.put("card_Type", "DebitCard");

        String json = convert(paymentCards); //converting Map to JSON String
        System.out.println("Map to JSON String");
        System.out.println("******************");
        printJson(json); 

        System.out.println();

        paymentCards = revert(json); //converting JSON String to Map
        System.out.println("JSON String to Map");
        System.out.println("******************");
        printMap(paymentCards);
    }

}

The output look like this:

2 of 4
10

Have a look at example 1.4 on this page http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-4_-_Encode_a_JSON_object_-_Using_Map_and_streaming:

 Map obj=new LinkedHashMap();
   obj.put("name","foo");
   obj.put("num",new Integer(100));
   obj.put("balance",new Double(1000.21));
   obj.put("is_vip",new Boolean(true));
   obj.put("nickname",null);
   StringWriter out = new StringWriter();
   JSONValue.writeJSONString(obj, out);
   String jsonText = out.toString();
   System.out.print(jsonText);
🌐
Java Guides
javaguides.net › 2023 › 10 › convert-json-string-to-map-in-java.html
Convert JSON string to Map in Java
October 26, 2023 - Java Programs Kotlin Programs C Programs R Programs Python Programs C++ Programs Go Programs TypeScript Programs JavaScript Programs ... Converting JSON strings to Java objects (and vice versa) is a frequent need in modern Java applications, especially when dealing with RESTful web services. In this tutorial, we'll look at how to use the Jackson library to convert a JSON string representing a user into a Java Map...
🌐
DevQA
devqa.io › how-to-convert-java-map-to-json
How to Convert Java Map to JSON
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; public class ConvertJavaMapToJson { @Test public void convertMapToJson() { Map<String, String> elements = new HashMap(); elements.put("Key1", "Value1"); elements.put("Key2", "Value2"); elements.put("Key3", "Value3"); ObjectMapper objectMapper = new ObjectMapper(); try { String json = objectMapper.writeValueAsString(elements); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } } }
🌐
Mkyong
mkyong.com › home › java › convert json string to map using jackson
Convert JSON string to Map using Jackson | mkyong.com
April 23, 2024 - package com.mkyong.json.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; import java.util.Map; public class MapToJsonExample { public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = new HashMap<>(); map.put("name", "mkyong"); map.put("age", 20); // convert map to JSON string String json = mapper.writeValueAsString(map); System.out.println(json); // compact-print // enable pretty-print json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map); System.out.println(json); // pretty-print } }
🌐
QA Automation Expert
qaautomation.expert › 2021 › 11 › 22 › serialization-how-to-convert-map-to-json-string-using-jackson-api
Serialization – How to convert Map to JSON string using Jackson API
December 8, 2022 - This tutorial shows how to convert a Java map to JSON string using Jackson’s data binding. In the previous tutorials, I explained converting Java Objects/Arrays to JSON String using Jackson API.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 49820057 › converting-json-string-to-map
java - Converting json string to map - Stack Overflow
Copystatic final String JSON_VAL="{\"A\":[{\"B\":[{\"C\":[{\"D1\":\"V1\",\"D2\":\"X1\",\"D3\":\"Y1\",\"D4\":\"Z1\"},{\"D1\":\"V2\",\"D2\":\"X2\",\"D3\":\"Y2\",\"D4\":\"Z2\"}]}]}]}"; final ObjectMapper mapper = new ObjectMapper(); final Wraper wraper = mapper.readValue(JSON_VAL, Wraper.class); final Map<String,List<String>> map = new HashMap<>(); Arrays.stream(wraper.a).forEach(a -> { Arrays.stream(a.b).forEach(b -> { final List<String> d1 = new ArrayList<>(); final List<String> d2 = new ArrayList<>(); final List<String> d3 = new ArrayList<>(); final List<String> d4 = new ArrayList<>(); Arrays.
🌐
Baeldung
baeldung.com › home › java › java collections › java map › convert hashmap to json object in java
Convert Hashmap to JSON Object in Java | Baeldung
January 8, 2024 - 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’s 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. ... Map<String, String> data = new HashMap<>(); data.put("CS", "Post1"); data.put("Linux", "Post1"); data.put("Kotlin", "Post1");
🌐
HowToDoInJava
howtodoinjava.com › home › jackson › jackson – marshal and unmarshal java maps
Jackson - Marshal and Unmarshal Java Maps - HowToDoInJava
August 20, 2022 - We are using HashMap here. HashMap<String, String> hashmap = new HashMap<String, String>(); hashmap.put("id", "1"); hashmap.put("firstName", "Lokesh"); hashmap.put("lastName", "Gupta"); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(hashmap);...
🌐
TutorialsPoint
tutorialspoint.com › article › how-can-we-convert-a-map-to-the-json-object-in-java
How can we convert a map to the JSON object in Java?
July 4, 2020 - We can convert a Map to JSON object using the toJSONString() method(static) of org.json.simple.JSONValue. It has two important static methods: writeJSONString() method to encode an object into JSON text and write it out, escape() method to escape ...
🌐
Baeldung
baeldung.com › home › json › jackson › map serialization and deserialization with jackson
Map Serialization and Deserialization with Jackson | Baeldung
January 8, 2024 - It allows us to serialize our map, and write it out as a pretty-printed JSON String using the toString() method in String: ... With a few extra steps, we can also serialize a map containing a custom Java class.
🌐
Educative
educative.io › answers › how-to-convert-a-json-string-to-a-map-using-jackson
How to convert a JSON string to a map using Jackson
Use the method readValue() of the ObjectMapper class, which takes in a JSON string and the class the string will be converted to. public <T> T readValue(String content, Class<T> valueType) String content: JSON string.
🌐
Java Guides
javaguides.net › 2023 › 10 › convert-map-to-json-array-string-in-java.html
Convert Map to JSON array string in Java
October 26, 2023 - In modern Java applications, especially with RESTful web services, there's often a requirement to convert Java objects into JSON format and vice versa. When representing data structures like a list of users in a user management system, converting a Map to a JSON array string becomes handy.