In the previous lesson, we covered converting Java Object to JSON. Here, you will learn how to convert JSON to Java Object using the ObjectMapper class from the Jackson library.
How to convert JSON to Java Object?
We will use the readValue() method from the ObjectMapper class.
There are a few overloaded readValue() methods. We will use the one that accepts the File and the one which accepts a String.
Example 1: Read a JSON from a file and convert it to Java Object.
First, let’s create a Student class:
class Student { private String name; private double grade; private String country; // constructors, getters and setters and toString method }
Note: We need the default constructor, getters, and setters methods for the Jackson conversion.
Jackson maps the fields by matching the names of the JSON fields to the getters and setters methods in the Java object.
Create a JSON file:
{ "name":"John", "grade":8.9, "country":"Italy" }
Now let’s read the JSON file and convert the content to a Student object.
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; class Test { public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); File file = new File("path_to_file/student.json"); Student student = objectMapper.readValue(file, Student.class); System.out.println(student); } }
Example 2: Convert a JSON String to Java Object
class Test { public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); String jsonString = "{\"name\":\"John\",\"grade\":8.9,\"country\":\"Italy\"}"; Student student = objectMapper.readValue(jsonString, Student.class); System.out.println(student); } }