×

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a map.

Since the JSON format is essentially a key-value pair grouping and the map similarly stores data in key-value pairs, we can easily convert JSON data into a map.

Let's examine how we can transform JSON data into a Map using the JACKSON and GSON libraries. Additionally, we comprehend how to use both frameworks to transform Map data into JSON.

{    
  "Name" : "Jhon",    
  "Mobile" : "987654321",    
  "Designation" : "Jhon Developer",    
  "Pet" : "cat",    
  "Address" : "INDIA"    
}    

JACKSON Library

  • <dependencies>
  • <dependency>
  • <groupno>com.fasterxml.jackson.core</groupno>
  • <artifactno>jackson-databind</artifactno>
  • <version>2.5.3</version>
  • </dependency>
  • </dependencies>

Let's use the ObjectMapper, File, and TypeReference classes to provide the logic for mapping JSON data to a map.

// importing required packages and classes
package solution.JavaExample;  
import java.io.File;    // for input and output operations
import com.fasterxml.jackson.databind.OM;  
import java.util.Map;  
import com.fasterxml.jackson.core.type.TypeReference;  
// to transform JSON data into a Java Map, develop the jack class.
public class Jack {  
    // execution starts from main() method 
    public static void main(String args[]) {  
        // create instance of the OM class to map JSON data  
        OM mapper = new OM();  
        // construct a File class instance
        F fileObj = new F("C:\\Users\\Jhon\\OneDrive\\Desktop\\Sam.json");  
        // To convert JSON data into Map, utilise a try-catch block.
        try {  
            // utilising the fileObj class to read JSON data from f and the OM and TypeReference classes to map it
            Map<String, Object>UD = mapper.readValue(  
fileObj, new TypeReference<Map<String, Object>>() {  
            });   
            // a list of every key-value pair
System.out.println("Name : " + UD.get("Name"));  
System.out.println("Mobile : " + UD.get("Mobile"));  
System.out.println("Designation : " + UD.get("Designation"));  
System.out.println("Pet : " + UD.get("Pet"));  
System.out.println("Address : " + UD.get("Address"));   
        } catch (Exception e) {  
            // error message display
e.printStackTrace();  
        }   
    }  
}  

Output:

Name: Jhon
Mobile:987654321
Desgination: Jhon developer
Pet: cat
Address: INDIA

Because we frequently need to deliver map data to APIs as JSON, let's look at another example from the Jackson library to better understand how we can transform a Java map into JSON. Therefore, we turn the Map data in this example into JSON and store it in a file.

JacksonConvertMapToJson.java

// importing required classes and packages  
package solution.JavaExample;  


import java.util.Map;  
import java.util.Scanner;  
import java.io.File;  
import java.util.HashMap;  


import com.fasterxml.jackson.databind.OM;  


//to convert Map data into JSON, create the Jack class.
public class Jack {  


    // executing start from main() method  
    public static void main(String args[]) {  


        // OM class instance creation
        OM mapper = new OM();  


        // Declare and launch the map (key is of type String and value is of type Object)
        Map<String, Object>UD = new HashMap<String, Object>();  


        // Declare variables and an array to hold the data entered by the user.
        String name, price, model;  
        String colors[];  


        // construct a Scanner class instance.
        Scanner n = new Scanner(System.in);  


        // taking user inputs and storing them in variables
System.out.println("Type the car's name here:");  
        name = n.nextLine();  


System.out.println("Type in the car's modal number:");  
        model = n.nextLine();  


System.out.println("Enter the car's price here:");  
        price = n.nextLine();  


        colors = new String[3];  
        colors[0] = "black";  
        colors[1] = "Brown";  
        colors[2] = "pink";  


        // Scanner class object, close
n.close();  


        // fill UD map  
UD.put("Car", name);  
UD.put("Price", price);  
UD.put("Model", model);  
UD.put("Colors", colors);  


       // Java map can be transformed into JSON using a try-catch block.
        try {  


            // to convert Map data to JSON and write it to the Sam.json file, use the OM class.
mapper.writeValue(new File("C:\\Users\\Jhon\\OneDrive\\Desktop\\Sam.json"), UD);  
System.out.println("Successful writing of map data to the Sam.json file.");  
        } catch (Exception e) {  
            // handling exception  
e.printStackTrace();  
        }   
    }  
}  

Output:

Console:
Type the car's name here:
BMW
Type in the car's modal number:
2022
Enter the car's price here:
77 lakhs
Successful writing of map data to the Sam.json file.


Sam- notepad
{“colors”:[“black”,”brown”,”pink”], “car”: “BMW”, “price”: “77 lakhs”, “model”: “2022”}

Gson Library

Another package we can use to turn JSON data into maps or maps into JSON is the Gson library. The following dependency needs to be added to our POM.xml file in order for us to use the Gson library.

<dependencies>
<dependency>
<groupno>com.google.code.gson</groupno>
<artifactno>gson</artifactno>
<version>2.8.3</version>
</dependency>
</dependencies>
GsonConvertJSONToMap.java


//importing required classes and packages  
package solution.JavaExample;  
import java.io.IOException;  
import java.nio.file.Files;    
import java.util.HashMap;  
import java.util.Map;  
import com.google.gson.Gson;  
import com.google.gson.reflect.TypeToken;  
import java.nio.file.Paths;    


//to transform JSON data into a Java Map, build the Gson class
public class Gson {  
    // executing starts from main() method  
    public static void main(String args[]) {  
        // create a variable called loc that stores the Sam.json file's location.
        String p = "C:\\Users\\Jhon\\OneDrive\\Desktop\\Sam.json";  
        String result;  
        try {  
            // read the Sam.json file's byte data and convert it to String
            result = new String(Files.readAllBytes(Paths.get(p)));  
            // use the TypeToken class to store string data in a Map.
             Map<String, Object>UD = new Gson().fromJson(result, new TypeToken<HashMap<String, Object>>() {  
                        }.getType());   
             // a list of every key-value pair
System.out.println("Name : " + UD.get("Name"));  
System.out.println("Mobile : " + UD.get("Mobile"));  
System.out.println("Designation : " + UD.get("Designation"));  
System.out.println("Pet : " + UD.get("Pet"));  
System.out.println("Address : " + UD.get("Address"));  
        } catch (IOException e1) {  
            // TODO Automatic catch block generation
            e1.printStackTrace();  
        }  
    }  
}

Output:

Name: Jhon
Mobile: 987654321
Designation: Jhon developer
Pet: cat
Address: INDIA

For a better understanding of how to convert a Java map into JSON, let's look at another example from the Gson package. The Gson library differs slightly from the Jackson library in terms of usage.

GsonConvertMapToJson.java

//importing required classes and packages  
package solution.JavaExample;  
import java.util.Map;  
import java.util.Scanner;  
import java.io.File;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.util.HashMap;  
import com.google.gson.Gson;  
//create Gson class to convert Map data into JSON  
public class Gson {  
    // executing starts from main() method  
    public static void main(String args[]) {  
        // Declare and launch the map (key is of type String and value is of type Object)
            Map<String, Object>UD = new HashMap<String, Object>();  
            // Declare variables and an array to hold the data entered by the user.
        String name, price, model;  
        String colors[];  
        // construct a Scanner class instance.
        Scanner n = new Scanner(System.in);  


        // taking user inputs and storing them in variables
System.out.println("Type the car's name here:");  
        name = n.nextLine();  


System.out.println("Type in the car's modal number:");  
        model = n.nextLine();  


System.out.println("Enter the car's price here:");  
        price = n.nextLine();  


        colors = new String[3];  
        colors[0] = "black";  
        colors[1] = "Brown";  
        colors[2] = "pink";  


        // closing Scanner class object  
n.close();  


        // fill UD map  
UD.put("Car", name);  
UD.put("Price", price);  
UD.put("Model", model);  
UD.put("Colors", colors);  


    // Java map can be transformed into JSON using a try-catch block.
                try (FileWriter file = new FileWriter("C:\\Users\\ Jhon\\OneDrive\\Desktop\\Sam.json")) {  
                    // create instance of the G 
                    G gsonObj = new G();  
                        // convert UD map to json string  
                    String jsonStr = gsonObj.toJson(UD);  
                        // To write a json string into a file, use File's write() method.
file.write(jsonStr);   
            // use flush() method to flushes stream  
file.flush();  
System.out.println("Successful writing of map data to the Sam.json file.");  
    } catch (IOException e) {  
                        // error handling and exceptions   
e.printStackTrace();  
            }  
    }  
}  

Output:

Console:
Type the car's name here:
BMW
Type in the car's modal number:
2022
Enter the car's price here:
77 lakhs

Sam:

{“colors”:[“black”,”brown”,”pink”], “car”: “BMW”, “price”: “77 lakhs”, “model”: “2022”}


Related Topics

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.