Converting Java Object to and from JSON using Jackson JSON library

47 Flares Twitter 0 Facebook 3 Google+ 44 LinkedIn 0 Filament.io 47 Flares ×

Jackson is a multipurpose java library for proccesisng JSON data format. Jackson offers three methods for processing JSON. You may use any of the techniques.

  1. Streaming API – reads and writes JSON content as discrete events. This is the best performing method.
  2. Tree Model – Similar to XML DOM. Provides an in-memory mutable tree model of the JSON data. More convenient.
  3. Data Binding –  converts JSON to and from POJOs based either on property accessor conventions or annotations. Most flexible.

Getting Jackson Libraries

Jackson Maven Dependency

<repositories>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/org/codehaus</url>
</repository>
</repositories>

<dependencies>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
</dependencies>

For non maven users, you can download the Jackson library from here

To Convert a JSON to Java Object you need to use the readValue method of  ObjectMapper and to Convert Java Object to JSON String it is the writeValue method that needs to be used.

Let us see how we can convert a JSON String to Java Object.

Consider the JSON

Our first task is to convert this JSON Data to a Java Object. For this we need to create a POJO matching the structure of the JSON String. In this case we create a User POJO

Java Client – JSON to Java Object

Java Object to JSON