Convert Java object to JSON using Jackson

Jackson is a standard library for handling JSON-related issues in Java. In this tutorial, we will learn how to convert Java objects to JSON using the Jackson library.

First, I will illustrate with a Maven project as follows:

Jackson dependency is as follows:

The current Application class has the following contents:

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:

OK, let’s get started on our topic.

First, we need to initialize a Student object:

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:

and use its writeValueAsString() method to convert a Student object to a JSON string:

Result:

Convert Java object to JSON using Jackson

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:

At this point, the result will be:

Convert Java object to JSON using Jackson

Add Comment