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.
Java JSON Jackson – 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.
Java JSON Jackson – Parsing JSON
The first 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.
- 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.
- 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
- 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.
Java JSON Jackson Annotation and Serialization
Jackson provides certain features that make the API extremely useful and flexible. These features are
- List Serialization – Serialization list can be tricky if type info is to be preserved. Look at this example to see how to do that.
- Annotation and Dynamic beans – Serialize unknown properties of json into a Map in the Java Object.
- 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.
- 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.
- 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.