In the previous post you saw How we converted Java Object to JSON.
Now lets see how to Convert JSON to Java Object using Jackson.
You will need the same dependency or Jar files that were mentioned in the previous post.
In the below example we will convert 2 JSON files.
1. JSON file with only one Employee Object.
2. JSOn file with a list of Employee Objects.
Using the ObjectMapper Class and its method readValue() we will be converting the json to java.
JSON Files
1. Single Employee – (SingleJSON.json)
1 |
{"empId":1,"name":"John Doe","department":"Sales"} |
2. List of Employees – (ListJson.json)
1 2 3 4 5 |
[ {"empId":1,"name":"John Doe","department":"Sales"}, {"empId":2,"name":"Smith T","department":"Management"}, {"empId":3,"name":"Scott Tiger","department":"HR"} ] |
JSONToJavaObject
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.kscodes.json.jackson; import java.io.File; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; public class JSONToJavaObject { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper(); try { //1. Convert JSON file that has only one java object File singleJsonFile = new File("C:\\kscodes\\SingleJSON.json"); Employee employee = mapper.readValue(singleJsonFile, Employee.class); System.out.println("Printing Single Employee"); System.out.println("Employee Object " + employee); System.out.println("-----------------------------"); //2. Convert JSON file that has a list of Java objects File lstJsonFile = new File("C:\\kscodes\\ListJson.json"); List<Employee> lstEmployee = mapper.readValue(lstJsonFile, List.class); System.out.println("Printing List Of Employees"); System.out.println(lstEmployee); } catch (Exception e) { System.out.println("Exception occurred while reading JSON File"); System.out.println("Exception::" + e); } } } |
Output
1 2 3 4 5 6 7 |
Printing Single Employee Employee Object Employee [empId=1, name=John Doe, department=Sales] ----------------------------- Printing List Of Employees [{empId=1, name=John Doe, department=Sales}, {empId=2, name=Smith T, department=Management}, {empId=3, name=Scott Tiger, department=HR}] |
Please Note :
If your Java Class doesnt have a Default Construtor, and you try to use the mapper.readValue to convert JSON to that Java class you will get the following exception
1 2 3 |
Exception::com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.kscodes.json.jackson.Employee: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?) |
So add a default for any User defined Objects that you need to convert JSON into.