How to Build Your First Application in Jackson

0
2767
Jackson

Jackson

In the last chapter, we discussed about the Jackson API including its overview, features and setup of our local environment using the Maven plugin and eclipse as IDE (Integrated Development Environment). In this tutorial, we are going to build our first Java based application using Jackson API. We are going to use the same environment which we had prepared in the last tutorial.

Example on Jackson API based application
In the following example, we have created an Employee class. The Employee class has five attributes , name, empId, designation, salary, grade, and age. Next, we have created a JSON string with Employee details. Firstly, we have conducted the deserialization of JSON string into an Employee object and then its serialization of Object back to a JSON string.

Employee.java

JacksonDemo.java

Output: – When we execute the above JacksonDemo class as a Java Application, we can observe the following output.

Explanation of the code
Step 1: – Creation of the ObjectMapper Object as shown below. It is a reusable object.

Step 2: – Deserialization of the JSON to Object. Here, we have used readValue () method in order to procure the Object from the JSON. It accepts two parameters. They are the JSON string or the source of the JSON string and the object type (here Employee.class).

Step 3: – Serialization of the Object back to JSON. Here, we have used writeValueAsString () method in order to get the JSON string representation of an object.

Source code to build our java based application using Jackson API

Conclusion: –
In this chapter, we have built a simple Jackson based Java application where we have use used the ObjectMapper class of Jackson API to conduct the deserialization of JSON to an Object (here Employee class object) and then its serialization back to a JSON string by using the appropriate methods as discussed before.

LEAVE A REPLY

Please enter your comment!
Please enter your name here