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”}