How to convert JSON to a Map object: Most of the time we have to communicate with other applications using the web services, and web services basically uses two ways to communicate with application one is using xml file and other is json.
So the question is how to convert json object to raw objects like Map ? The answer of this question is simple use Jackson api to process the json objects, and convert it to a Map object.
To use Jackson api in our project we need to download the following jars :
jackson-databind-2.2.3.jar
jackson-core-2.2.3.jar
jackson-annotations-2.2.3.jar
Or we can use maven dependency in our project, put following code in pom.xml :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
In our example we are converting JSON to Map Object. Here we are using json document, and using this we will map that json object to Map.class object.
Example to convert Json to a Map object :
We will write the code to convert the json object to row class like Map, ArrayList etc. In this example ObjectMapper takes the json document and map the json object to Map.class object.
JsonToMap.java
package com.evon.jakson.conversion;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToMap {
public static void main(String[] args) throws IOException {
String filePath = "/home/user/employee.json";
//converting json to Map
ObjectMapper objectMapper = new ObjectMapper();
Map<String,Object> userData = objectMapper.readValue(new File(filePath), Map.class);
System.out.println("Map is: "+userData);
}
}
In the above code we are passing a file called employee.json which is having the json object and ObjectMapper is a class file of Jackon's api which map the json object to the Map.class.
Output :
Map is: {id=1, name=Sumit, occupation=Software Engineer}
0 Comment(s)