Jackson is a standard library for handling JSON-related issues in Java. In this tutorial, we will learn how to convert Java object to JSON using Jackson library.
First, I will illustrate with a Maven project as follows:
Jackson dependency as follows:
1 2 3 4 5 |
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.0</version> </dependency> |
The current Application class has the following contents:
1 2 3 4 5 6 7 8 |
package com.huongdanjava.jackson; public class Application { public static void main(String[] args) { } } |
Since we are converting a Java object to a JSON string, the first thing we need to do is to define a Java object. I have defined a Student class in the com.huongdanjava.jackson package as simple as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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; } } |
OK, let’s get started on our topic.
First, we need to initialize a Student object:
1 2 3 |
Student student = new Student(); student.setName("Khanh"); student.setAge(30); |
To convert this Student object to a JSON string, I would use the ObjectMapper object in the Jackson library to do this.
We will initialize it first:
1 |
ObjectMapper om = new ObjectMapper(); |
and use its writeValueAsString() method to convert a Student object to a JSON string:
1 2 |
String json = om.writeValueAsString(student); System.out.println(json); |
Result:
If you want the resulting JSON string to be better formatted then you can use the ObjectMapper object and call the writerWithDefaultPrettyPrinter() method before calling the writeValueAsString() method:
1 2 3 |
ObjectMapper om = new ObjectMapper(); String json = om.writerWithDefaultPrettyPrinter().writeValueAsString(student); System.out.println(json); |
At this point, the result will be: