How to Convert Map to JSON to HashMap in Java?
Last Updated :
04 Aug, 2022
JSON is an open standard file format, and easier data interchange format helpful for humans to transmit data. Most of the apps display JSON data and hence nowadays JSON has become the mandatory media to transmit data. Here we will get to know how to convert Map to JSON and for Map, let us take HashMap as an input set of data.
Installation:
Step 1: For console-related Java parts, we need the jar downloads from the links provided below. Download the jars, extract them and place the jars in the build path of a project
http://www.java2s.com/Code/Jar/j/Downloadjacksonannotations212jar.htm
http://www.java2s.com/Code/Jar/c/Downloadcomfasterxmljacksondatabindjar.htm
Step 2(A): For Maven projects, the following dependency is needed in the ‘pom.xml file.’
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
Step 2(B): For Gradle projects, it is as follows:
dependencies
{
// a dependency on Jackson Databind
implementation 'com.fasterxml.jackson.core:jackson-databind:2.8.9'
}
Implementation:
Let us see an example of HashMap of data. HashMap advantage is storing the data in key, value pairs in an unsynchronized way.
We are going to have studentId,studentFirstName,studentLastName,studentStream and studentMarks as the key elements of HashMap. Using com.fasterxml.jackson.databind.ObjectMapper, we are converting the HashMap into JSON. Let us see a simple Java application. ObjectMapper is the main essential class in the Jackson library that helps for reading and writing JSON, either to and from basic POJO’s (Plain Old Java Objects) or from HashMap containing key/value pairs.
Here we will be using a method named ‘writeValueAsString()’ in the code and that can be used to serialize any Java value as a String. Here we are passing HashMap of data as objects, and it serializes them as strings. As ObjectMapper is used, it writes JSON string.
Example 1:
Java
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
public class GFG {
public static void main(String[] args)
{
HashMap<String, Object> studentHashmap
= new HashMap<String, Object>();
studentHashmap.put( "studentId" , 1 );
studentHashmap.put( "studentFirstName" , "AAA" );
studentHashmap.put( "studentLastName" , "BBB" );
studentHashmap.put( "studentStream" , "PCMB" );
studentHashmap.put( "studentMarks" , "480" );
ObjectMapper mapper = new ObjectMapper();
try {
String studentJson
= mapper.writeValueAsString(studentHashmap);
System.out.println(studentJson);
}
catch (JsonGenerationException e) {
e.printStackTrace();
}
catch (JsonMappingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
Output:
Moving forward to the next example. In this example, let us see how JSON data is converted to Map using ObjectMapper. We will be using readValue() here that will deserialize JSON content into a non-container type. Here in this example as a Map class, JSON content is deserialized.
readValue(JsonParser p, Class<T> valueType)
Example 2:
Java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
public class GFG {
public static void main(String[] args)
{
ObjectMapper mapper = new ObjectMapper();
String studentJsonData
= "{\"studentId\":\"1\", \"studentFirstName\":\"AAA\",\"studentLastName\":\"BBB\",\"studentStream\":\"PCMB\",\"studentMarks\":\"480\"}" ;
try {
Map<String, String> studentMapData
= mapper.readValue(studentJsonData,
Map. class );
System.out.println(studentMapData);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
Output:
Output explanation:
Here as we have seen in example 1 and example 2 has the possibility of producing JsonMappingException which may occur when “Can Not Construct Instance Of”/” No Suitable Constructor”/” Root Name Does Not Match Expected”/” No Serializer Found for Class” etc. So whenever conversion from HashMap to JSON or JSON to HashMap is there, there are possibilities of the above exception and hence we need to handle it. Apart from that JsonGenerationException and IOException also possible, and we need to handle it
Moving forward to the next example, let us consider a bit of a complex example and provide the results via JunitTestCase. Here we are deserializing JSON content into the POJO class
Example 3(A): POJO classes namely Automobiles.java containing 3 attributes namely color/type/name
Java
public class Automobiles {
private String color;
private String type;
private String name;
public Automobiles() {}
public Automobiles( final String color,
final String type, final String name)
{
this .color = color;
this .type = type;
this .name = name;
}
public String getName() { return name; }
public void setName(String name) { this .name = name; }
public String getColor() { return color; }
public void setColor( final String color)
{
this .color = color;
}
public String getType() { return type; }
public void setType( final String type)
{
this .type = type;
}
}
|
Now let us write JunitTestCases and check how DeserializationFeature is working out in the below example as follows:
Example 3(B):
Java
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
public class
SerializationDeserializationFeatureUnitTestExample {
final String EXAMPLE_JSON
= "{ \"color\" : \"Black\", \"type\" : \"BMW\" }" ;
final String JSON_CAR
= "{ \"color\" : \"Red\", \"type\" : \"Honda WRV\", \"year\" : \"2018\" }" ;
final String JSON_ARRAY
= "[{ \"color\" : \"Blue\", \"type\" : \"Sedan\",\"name\" : \"Honda City\" }, { \"color\" : \"Red\", \"type\" : \"Hatchback\",\"name\" : \"Santro\" }]" ;
@Test
public void
whenFailOnUnkownPropertiesFalse_thanJsonReadCorrectly()
throws Exception
{
final ObjectMapper objectMapper
= new ObjectMapper();
objectMapper.configure(
DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES,
false );
final Automobiles automobiles
= objectMapper.readValue(JSON_CAR,
Automobiles. class );
assertNotNull(automobiles);
}
@Test
public void
whenUseJavaArrayForJsonArrayTrue_thanJsonReadAsArray()
throws Exception
{
final ObjectMapper objectMapper
= new ObjectMapper();
objectMapper.configure(
DeserializationFeature
.USE_JAVA_ARRAY_FOR_JSON_ARRAY,
true );
final Automobiles[] automobiles
= objectMapper.readValue(JSON_ARRAY,
Automobiles[]. class );
for ( final Automobiles car : automobiles) {
assertNotNull(car);
}
assertTrue(
automobiles[ 1 ].getName().equalsIgnoreCase(
"Santro" ));
assertTrue(
automobiles[ 0 ].getType().equalsIgnoreCase(
"Sedan" ));
}
}
|
Output: After running these JUnits
Conclusion: Construction of Map to JSON and the reverse way of JSON to Map are the standard mechanisms followed in the software industry. They are very useful in many places of software projects.
Share your thoughts in the comments
Please Login to comment...