In my previous tutorial, I showed you how to convert Java object to JSON using the Jackson library. So what if we wanted to do the reverse, ie converting JSON to Java object? In this tutorial, we will learn more about that.
As an example, we also have a project similar to the previous tutorial as follows:
Jackson dependency:
1 2 3 4 5 |
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.18.1</version> </dependency> |
Class Application to run for example:
1 2 3 4 5 6 7 8 |
package com.huongdanjava.jackson; public class Application { public static void main(String[] args) { } } |
And the Student class is the object that will store the converted information from the JSON string.
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 |
package com.huongdanjava.jackson; public class Student { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } } |
Of course, we also have a JSON string as follows:
1 |
{"name":"Khanh","age":30} |
OK, now we can start our main mission.
First, we will also create a new Jackson’s ObjectMapper object:
1 |
ObjectMapper om = new ObjectMapper(); |
And use the ObjectMapper’s readValue() method to convert the JSON string to a Java object:
1 2 |
Student obj = om.readValue(json, Student.class); System.out.println(json); |
Result: