Jackson: Introduction

Overview of The Jackson API

Jackson Api contains a lot of functionalities to read and build json using java. It has very powerful data binding capabilities and provides a framework to serialize custom java objects to json string and deserialize json string back to java objects. Json written with jackson can contain embedded class information that helps in creating the complete object tree during deserialization.

Creating JSON from JAVA

There are three ways to create JSON from JAVA:

  • From a Java Object (The Same object can also be then used to read the JSON)
  • From a JsonNode Tree
  • Building a Json Stream

In the first tutorial we look at all the three ways of creating JSON. Note that if you are new to Jackson this is probably the best place to begin even if you are looking at a way to parse JSON.

Parsing JSON

The previous tutorial showed how to convert a java object to JSON. the same java object can then be used to bind the json to java. However, as the author of jackson points out, there are three ways to parse JSON using Jackson.

  1. Streaming - use the JsonParser to parse the json stream. It provides the json elements as tokens. Use the JsonGenerator to generate the json from string, integer, boolean etc.
  2. Tree Traversing - the compete json can be read into a JsonNode. The node can then be traversed to get the required property. A tree can also be created and then written as json string
  3. Data Binding - Binding the Json to custom java objects (POJO). Jackson offers a lot of flexibility around these. Annotation can be used to mark properties and constructors on the POJO.

Jackson provides certain features that make the API extremely useful and flexible. These features are

  1. List Serialization - Serialization list can be tricky if type info is to be preserved. Look at this example to see how to do that.
  2. Annotation and Dynamic beans - Serialize unknown properties of json into a Map in the Java Object.
  3. Annotation Filters - While data binding, properties of the POJO can be ignored or filtered out. These filters can be set using annotation on the POJO or by using custom filters in the calling class.
  4. Mix-in - Annotations on POJO can be used to map the POJO properties to Json properties and to also mark constructors for use during data binding. However, what if the POJO is from a third party, and cannot be annotated. Mix-in comes to the rescue. It provides a way to annotate third party classes.
  5. Polymorphic Behaviour - If a Json is created using objects that are specific instances of an abstract class, then Jackson provides a way to create the exact subclass

The subsequent tutorials provides examples for each of the above cases.

(Note: This article’s original links is here )

 XStream: XML Transformation Jackson: Java to JSON and back 


©2015-2022 Alimy All rights reserved.