Convert Java Object to/from JSON using JACKSON API

In this tutorial, we will show you how to use Jackson 2.x to convert Java object to/from JSON using Jackson API.

The class ObjectMapper is the main api of Jackson 2.x used for data-binding. It comes with several reader/writer methods to preform the conversion from/to Java and JSON.

Other interesting posts you may like

Quick Reference

Convert Java object to JSON using the writeValue() method

Convert JSON to Java object using the readValue() method

JACKSON dependency in pom.xml

We will use the below Jackson dependency form data-bind.

Create POJO (Plain Old Java Object)
We will use these Java class to Convert JSON to/from Java Objects.

Convert Java Object to JSON and write JSON to a file

Convert Fruit object into JSON and write that JSON to a file

Run above program. The screen shot is the output written in file fruit.json

Convert JavaObject To Json Example

Pretty print JSON
The above output is not very readable. But you can print pretty JSON using writerWithDefaultPrettyPrinter factory method of ObjectMapper.

Convert JavaObject To Json Example pretty

Read JSON from a file and convert into Java Object

Read JSON string from a file and convert into Fruit object.

Following is the output:

Convert Json To JavaObject Example

That’s it. In the next post we will learn how Json can be mapped to Java Maps.

Download source code, click link below

2 thoughts on “Convert Java Object to/from JSON using JACKSON API”

Leave a Comment


Please share it if you found this useful
Hide Buttons