×

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

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.