How To Convert JSON To Map In Java

In the Java programming language, JSON (JavaScript Object Notation) is a widely used format for exchanging data between systems. It provides an easy way to represent complex data structures in a simple and human-readable format.

Converting JSON to a Map is a common requirement when working with JSON data in Java. In this tutorial, we will explore different approaches to convert JSON to Map in Java.

While choosing the final approach, consider the following factors such as size and complexity of the JSON data, speed and efficiency requirements and availability and familiarity with the required libraries.

Converting JSON to Map can be useful in the following scenarios:

  • Extracting values: When working with JSON data, we need to extract certain values from it.
  • Manipulating data: When we want to manipulate JSON data as a Map instead of a raw string.
  • Passing data to methods: When we need to pass JSON data to methods that expect Map as input.

Different Approaches on how to convert JSON to map in Java

There are several ways to convert JSON to Map in Java, including:

  1. Manually parsing JSON string.
  2. Using the org.json library provided by Java.
  3. Using the Jackson library

Approach 1:  Manually parsing JSON string

You can convert a JSON string to a Map in Java without using external libraries, although it requires some extra code to parse the JSON string. The approach involves manually parsing the JSON string by iterating over the key-value pairs and adding them to a Map.

Note that this implementation assumes that the JSON string contains only simple key-value pairs, and does not handle nested objects or arrays.

Sample Code:

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

public class JsonToMap {
    public static void main(String[] args) {
        String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; //input

        Map<String, Object> map = new HashMap<>();

        // Remove curly braces and split key-value pairs
        String[] pairs = json.substring(1, json.length() - 1).split(",");

        // For each key-value pair, split it into key and value
        for (String pair : pairs) {
            String[] keyValue = pair.split(":");
            String key = keyValue[0].replaceAll("\"", "").trim();
            String value = keyValue[1].trim();
            if (value.startsWith("\"") && value.endsWith("\"")) {
                // If value is a string, remove surrounding quotes
                value = value.substring(1, value.length() - 1);
            }
            map.put(key, value);
        }
        System.out.println(map); 
    }
}

Output:

 {city=New York, name=John, age=30}

Code Explanation:

  • Create an empty Map to hold the key-value pairs.
  • Remove the curly braces from the JSON string using substring.
  • Split the string into key-value pairs using ,
  • For each key-value pair, split it into key and value using split.
  • Remove the surrounding quotes from the key and value using replaceAll and trim.
  • If the value is a string, remove the surrounding quotes using substring.
  • Add the key-value pair to the Map using put.

Approach 2: Using the org.json library

The approach involves using the JSONObject class provided by the org.json library to convert the JSON string to a Map.

Note that the JSON object is converted to a Map<String, Object>. If your JSON contains nested objects or arrays, the resulting Map will contain nested Maps or Lists.

Note: You will need to have the org.json library in your classpath in order to run the code

Sample Code:

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

public class JsonToMapDemo {
   public static void main(String[] args) {
      String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";   // input
      JSONObject jsonObject = new JSONObject(jsonString);
      Map<String, Object> map = new HashMap<String, Object>();
         // iterate over the key set of the JSONObject and add each key-value pair to the HashMap
      jsonObject.keySet().forEach(key -> map.put(key, jsonObject.get(key)));
      System.out.println("Map from JSON: " + map);
   }
}

Output:

Map from JSON: {city=New York, age=30, name=John}

Code Explanation:

  • First, we define a JSON string that we want to convert to a map.
  • Then, we create a JSONObject by passing the JSON string to its constructor.
  • After that, we create a new instance of the HashMap class to store the key-value pairs from the JSONObject.
  • We iterate over the key set of the JSONObject and add each key-value pair to the HashMap.
  • Finally, we print the resulting map.

Approach 3: Using Jackson Library

Jackson is a popular JSON processing library for Java that provides various features for working with JSON data. Jackson library is a widely used library for JSON processing in Java. It provides several other features, such as streaming API, data binding, and tree model, which can be used for more complex use cases. Using Jackson, we can easily convert JSON data to a Map in Java.
Note: You will need to have the Jackson library in your classpath in order to run the code

Sample Code:

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

public class JsonToMapConverter {
    public static void main(String[] args) throws Exception {
        String json = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"Anytown\",\"state\":\"CA\",\"zip\":\"12345\"}}";        // input

        ObjectMapper objectMapper = new ObjectMapper();
         //  calling the readValue() method of the ObjectMapper class and passing the JSON string and  
         //  the Map class as arguments
        Map<String, Object> map = objectMapper.readValue(json, Map.class);

        System.out.println(map);
    }
}

Output:

{name=John, age=30, address={street=123 Main St, city=Anytown, state=CA, zip=12345}}

Code Explanation:

  • We first create a String variable json that contains our JSON data.
  • We create an instance of the ObjectMapper class.
  • We call the readValue() method of the ObjectMapper class, passing the JSON string and the Map class as arguments. This method parses the JSON data and returns a Map object containing the key-value pairs.
  • We print the resulting Map object.

Best Approach for “how to convert JSON to map in Java”

After considering all the approaches, the best approach is using the Jackson library. Here are some of the pros of using the Jackson library compared to the other two approaches:

  • Efficient: Faster and more efficient in handling large JSON files
  • Flexible: More flexible and customizable
  • Versatile: Better support for handling different data types, including nested objects and arrays
  • Error handling: Provides better error handling and debugging options
  • Community support: Has a larger and more active community for support and updates.

Sample Problems in parsing JSON to map in Java

Sample Problem 1: Manually parsing JSON string

Suppose you are working on a project where you receive customer feedback in the form of a JSON string. You need to extract specific information such as the customer’s name, feedback message, and rating from the JSON string and store it in a database.

Input: 

String jsonString = "{\"name\":\"Emily\", \"feedback\":\"Great service! The staff was very helpful.\", \"rating\":4.5}";

Solution:

  • The approach involves manually parsing the JSON string by iterating over the key-value pairs and adding them to a Map without using any libraries.
  • The steps involved in this approach are:
  • Remove the starting and ending curly braces from the JSON string.
  • Split the JSON string into key-value pairs.
  • Iterate over each key-value pair and split it into key and value.
  • Remove the double quotes from the key and trim any spaces.
  • Check the type of value and convert it to the corresponding type.
  • Add the key-value pair to the Map.
  • Extract the required information from the Map.

Solution Code:

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

public class ManualJSONParser {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"Emily\", \"feedback\":\"Great service! The staff was very helpful.\", \"rating\":4.5}";
        Map<String, Object> jsonMap = new HashMap<>();

        //remove starting and ending curly braces
        jsonString = jsonString.substring(1, jsonString.length()-1);

        String[] keyValuePairs = jsonString.split(",");
        for(String pair: keyValuePairs){
            String[] entry = pair.split(":");
            String key = entry[0].replace("\"", "").trim();
            String value = entry[1].trim();
            Object objValue = null;

            //check the type of value and convert it to corresponding type
            if(value.startsWith("\"")){
                objValue = value.replaceAll("\"", "");
            }else if(value.contains(".")){
                objValue = Double.parseDouble(value);
            }else{
                objValue = Integer.parseInt(value);
            }
            jsonMap.put(key, objValue);
        }
        //print the extracted information
        System.out.println("Name: " + jsonMap.get("name"));
        System.out.println("Feedback: " + jsonMap.get("feedback"));
        System.out.println("Rating: " + jsonMap.get("rating"));
    }
}

Output:

Name: Emily
Feedback: Great service! The staff was very helpful.
Rating: 4.5

Sample Problem 2: Using the org.json library

A large organization has multiple departments and numerous employees. They want to keep track of the employee details including their name, department, and salary. The employee details are stored in a JSON format which needs to be converted into a map to be processed further. The organization wants to analyze the salary distribution of employees across departments to make informed decisions regarding salary hikes and promotions. You have to come up with a code solution to convert JSON object to map in Java.

Input String:

{ "employees":[
      {  "name":"John Doe",
         "department":"Marketing",
         "salary":5000
      },
      {  "name":"Jane Smith",
         "department":"IT",
         "salary":6000
      },
      {  "name":"Bob Johnson",
         "department":"Finance",
         "salary":7000
      } ] 
}

Solution:

  • We declare a string variable jsonString containing the JSON data.
  • We create an empty HashMap called result to store the converted JSON data.
  • We create a JSONObject from the jsonString and get the JSONArray containing the employees’ data.
  • We loop through each employee in the JSONArray and retrieve their name, department, and salary.
  • We create another HashMap called employeeMap to store the employee’s data.
  • We put the employee’s data in employeeMap with keys as name, department, and salary.
  • We put an employeeMap in the result with the key as the employee’s name.
  • We print the result, which contains the converted JSON data.

Solution Code:

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

public class JsonToMapDemo {
    public static void main(String[] args) {
        // define the input JSON string
        String jsonString = "{\"employees\":[{\"name\":\"John Doe\",\"department\":\"Marketing\",\"salary\":5000},{\"name\":\"Jane Smith\",\"department\":\"IT\",\"salary\":6000},{\"name\":\"Bob Johnson\",\"department\":\"Finance\",\"salary\":7000}]}";
        
        // create a new HashMap to store the result
        Map<String, Object> result = new HashMap<>();

        // create a new JSONObject from the input JSON string
        JSONObject jsonObject = new JSONObject(jsonString);
        
        // get the JSONArray for the "employees" key in the JSONObject
        JSONArray employeesArray = jsonObject.getJSONArray("employees");

        // iterate over each element in the JSONArray
        for (int i = 0; i < employeesArray.length(); i++) {
            // get the JSONObject for the current element
            JSONObject employee = employeesArray.getJSONObject(i);

            // extract the values for the "name", "department", and "salary" keys
            String name = employee.getString("name");
            String department = employee.getString("department");
            int salary = employee.getInt("salary");

            // create a new HashMap to store the values for the current employee
            Map<String, Object> employeeMap = new HashMap<>();
            employeeMap.put("name", name);
            employeeMap.put("department", department);
            employeeMap.put("salary", salary);

            // add the current employee to the result HashMap, with the name as the key
            result.put(name, employeeMap);
        }

        // print the final result HashMap
        System.out.println(result);
    }
}

Output:

{    John Doe={name=John Doe, department=Marketing, salary=5000}, 
    Jane Smith={name=Jane Smith, department=IT, salary=6000}, 
    Bob Johnson={name=Bob Johnson, department=Finance, salary=7000}
}

Sample Problem 3: Using a JSON library like Jackson

You are a developer working on a social media platform that allows users to create and share events with their friends. The platform has a feature where users can export the events they created in JSON format. One of your colleagues wants to use this data in their project, but they need to convert the JSON data to a Map object to use it.  You need to provide them with a solution on how to convert JSON object to Map in Java using Jackson library.

Input:

{    "events": [
        {    "id": "event_001",
            "name": "Birthday Party",
            "date": "2023-05-20",
            "location": {
                "city": "New York",
                "state": "NY"
            }
        },
        {   "id": "event_002",
            "name": "Graduation Ceremony",
            "date": "2023-06-15",
            "location": {
                "city": "Los Angeles",
                "state": "CA"
            }
        },
        {    "id": "event_003",
            "name": "Conference",
            "date": "2023-09-10",
            "location": {
                "city": "San Francisco",
                "state": "CA"
            }    }    ]
}

Solution:

We can solve this problem using the following given approach:

  • Jackson library provides an ObjectMapper class to convert JSON to Java objects and vice versa.
  • To convert JSON to a Map object using Jackson library, we need to use the readValue() method of the ObjectMapper class.
  • We need to pass the JSON string and TypeReference object as parameters to the readValue() method.
  • TypeReference object is used to provide type information to Jackson library to correctly deserialize the JSON string to a Map object.
  • The TypeReference object is parameterized with the types of keys and values in the Map object. In this case, we use String as the type of keys and Object as the type of values.

Solution Code:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;

public class JsonToMap {
    public static void main(String[] args) throws IOException {

        // input JSON data
        String json = "{\"events\":[{\"id\":\"event_001\",\"name\":\"Birthday Party\",\"date\":\"2023-05-20\",\"location\":{\"city\":\"New York\",\"state\":\"NY\"}},{\"id\":\"event_002\",\"name\":\"Graduation Ceremony\",\"date\":\"2023-06-15\",\"location\":{\"city\":\"Los Angeles\",\"state\":\"CA\"}},{\"id\":\"event_003\",\"name\":\"Conference\",\"date\":\"2023-09-10\",\"location\":{\"city\":\"San Francisco\",\"state\":\"CA\"}}]}";

        // create ObjectMapper instance
        ObjectMapper objectMapper = new ObjectMapper();

        // convert JSON string to Map using Jackson library
        Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>(){});

        // print the map object
        System.out.println("Map object: " + map);
    }
}

Output:

Map object: {events=[{id=event_001, name=Birthday Party, date=2023-05-20, location={city=New York, state=NY}}, {id=event_002, name=Graduation Ceremony, date=2023-06-15, location={city=Los Angeles, state=CA}}, {id=event_003, name=Conference, date=2023-09-10, location={city=San Francisco, state=CA}}]}

Conclusion on how to convert JSON to map in java

In this tutorial, we discussed how to convert JSON objects to Map in Java. Converting JSON to Map can be useful in various scenarios, including parsing JSON data from an API response, configuring Java applications using JSON files, and more. We explored three different approaches for converting JSON to Map in Java. While all three approaches can be used to convert JSON to Map in Java, we recommend using the Jackson library approach as it is faster, more versatile, and has great community support.

However, the choice of approach ultimately depends on the specific requirements of your project. We urge you to try all three approaches and choose the one that works best for your specific use case.