Convert JSON to Map in Java

Java provides two very strong libraries to work with JSON data, i.e., JACKSON and Gson libraries. We often need to convert JSON responses into a map to work with the returned JSON data easily.

We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs.

Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map. We also understand that how we can use both libraries to convert Map data into JSON.

Suppose, we have a Sample.json file in the system that contains the following data:

JACKSON Library

In order to convert JSON data into Java Map, we take help of JACKSON library. We add the following dependency in the POM.xml file to work with JACKSON library.

Let's implement the logic of converting JSON data into a map using ObjectMapper, File and TypeReference classes.

JacksonConvertJSONToMap.java

Output:

Convert JSON to Map in Java

Let's take another example of the Jackson library to understand how we can convert a Java map into JSON because we often need to pass map data to API as JSON. So, in this example, we convert Map data into JSON and store it in a file.

JacksonConvertMapToJson.java

Output:

Convert JSON to Map in Java
Convert JSON to Map in Java

Gson Library

Gson library is another library which we can use to convert JSON data into map or map data into JSON. In order to use Gson library, we need to add the following dependency in our POM.xml file.

GsonConvertJSONToMap.java

Output:

Convert JSON to Map in Java

Let's take another example of the Gson library to understand how to convert a Java map into JSON. Using the Gson library is a little different from the Jackson library.

GsonConvertMapToJson.java

Output:

Convert JSON to Map in Java
Convert JSON to Map in Java