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
// Java Program to Convert Map to JSON to HashMap // Importing required basic libraries // Importing required classes from com.fasterxml.jackson // package 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; // Main class // MapToJSONExample public class GFG { // Main driver method public static void main(String[] args) { // Creating an object of HashMap class // Declaring object of String and Object type HashMap<String, Object> studentHashmap = new HashMap<String, Object>(); // Let us hold studentHashmap containing // 1. studentId // 2. studentFirstName // 3. studentLastName // 4. studentStream // 5. studentMarks // Custom input entries studentHashmap.put( "studentId" , 1 ); studentHashmap.put( "studentFirstName" , "AAA" ); studentHashmap.put( "studentLastName" , "BBB" ); studentHashmap.put( "studentStream" , "PCMB" ); studentHashmap.put( "studentMarks" , "480" ); // ObjectMapper object is a reusable object. // ObjectMapper is the main essential class in // Jackson library which helps for reading and // writing JSON, either to and from basic POJOs // (Plain Old Java Objects) or from HashMap // containing key/value pairs. ObjectMapper mapper = new ObjectMapper(); // Try block to check for exceptions try { // Convert studentHashmap to JSON // In method writeValueAsString(Object object), // we are using this method in the code and that // can be used to serialize any Java value as a // String. Here we are passing HashMap of data // as object and it serializes them as string . // As ObjectMapper is used, it writes JSON // string String studentJson = mapper.writeValueAsString(studentHashmap); // Print JSON output System.out.println(studentJson); } // There are possibilities of following exceptions, // so catch block to handle the exceptions catch (JsonGenerationException e) { // Printing the exception along with line number // using the printStackTrace() method e.printStackTrace(); } // Catch block 2 catch (JsonMappingException e) { e.printStackTrace(); } // Catch block 3 // Catching generic input output exceptions 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
// Java Program to Convert Map to JSON to HashMap // Importing utility and input output classes // Importing ObjectMapper class import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Map; // Main class // To convert JSON to Map public class GFG { // Main driver method public static void main(String[] args) { // Creating an object of ObjectMapper class // in the main() method ObjectMapper mapper = new ObjectMapper(); // Custom string data in JSON String studentJsonData = "{\"studentId\":\"1\", \"studentFirstName\":\"AAA\",\"studentLastName\":\"BBB\",\"studentStream\":\"PCMB\",\"studentMarks\":\"480\"}" ; // Try block to handle the exceptions try { // Convert JSON string to Map // This method deserializes JSON content into a // non-container type. In our example as a Map // class, JSON content is deserialized. Map<String, String> studentMapData = mapper.readValue(studentJsonData, Map. class ); System.out.println(studentMapData); } // Catch block to handle the exceptions catch (IOException e) { // Display and print the exceptions along with // line number using printStackTrace() method 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
// Java Program illustratiing Simple POJO class only // containing 3 attributes namely color/type/name public class Automobiles { // Any kind of automobiles can have these attributes and // for simplicity let us keep this private String color; private String type; private String name; // Constructor 1 // Default constructor of this class public Automobiles() {} // Constructor 2 // Parameterized constructor of this class public Automobiles( final String color, final String type, final String name) { // This keyword refers to current instance itself this .color = color; this .type = type; this .name = name; } // Method 1 public String getName() { return name; } // Method 2 public void setName(String name) { this .name = name; } // Method 3 public String getColor() { return color; } // Method 4 public void setColor( final String color) { this .color = color; } // Method 5 public String getType() { return type; } // Method 6 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
// Java Program to Convert Map to JSON to HashMap 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 { // ObjectMapper is the main essential class in // Jackson library which helps for reading and // writing JSON, and in this example it is from POJO // class that is our Automobiles class final ObjectMapper objectMapper = new ObjectMapper(); // Reason for setting // DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES // to false is that it will tell Jackson to ignore // unknown attributes in all deserializations where // that object mapper is used. objectMapper.configure( DeserializationFeature .FAIL_ON_UNKNOWN_PROPERTIES, false ); // readValue(JsonParser p, Class<T> valueType) - // This method deserializes JSON content into a // non-container type. In our example it is // Automobiles class, JSON content is deserialized. final Automobiles automobiles = objectMapper.readValue(JSON_CAR, Automobiles. class ); assertNotNull(automobiles); } @Test public void whenUseJavaArrayForJsonArrayTrue_thanJsonReadAsArray() throws Exception { final ObjectMapper objectMapper = new ObjectMapper(); // Reason for setting // DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES // to true is that it will tell Jackson to consider // attributes in all deserializations where that // object mapper is used. 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.