This tutorial introduces about JSON Annotations via Jackson JSON Annotation Example. Jackson JSON Annotations are implemented exactly as approach read and write of JSON data-binding. But the different point is properties of POJO are annotated at running time.
Other interesting posts you may like
Table of contents:
1. Project structure
1. JACKSON dependency
2. Create input JSON
3. Create POJO with JSON annotations
4. Create Custom Serializer
5. Create Main
Project structure
We will create project structure like this:
JACKSON dependency
The jackson-databind provides ObjectMapper API and the jackson-annotations provides JSON annotations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode.jackson</groupId> <artifactId>Jackson-Json-Annotation-Example</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Jackson-Json-Annotation-Example - ${project.artifactId}</name> <packaging>jar</packaging> <dependencies> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.0</version> </dependency> </dependencies> </project> |
Create input JSON
We create a file named fruit.json that contains content like this:
1 |
{"name":"Apple","cost":0,"produceby":["Indonesia","Combodia","Peru"],"importedDate":1471915181170,"fruitPackage":{"name":"Fruit Punnets","quantityNet":5}} |
Create POJO with JSON annotations
Using JSON annotations is the most important point in the Jackson Json Annotation Example. We create POJO with JSON annotations such as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package com.javabycode.jackson; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonIgnoreProperties({ "flavor" }) public class Fruit { @JsonProperty private String name; @JsonProperty("costPrice") private long cost; @JsonProperty private List produceby = new ArrayList(); @JsonProperty @JsonSerialize(using = MyCustomDate.class) private Date importedDate; private String flavor; private Map<String, Object> fruitPackage = new HashMap<String, Object>(); @JsonAnyGetter public Map<String, Object> any() { return fruitPackage; } @JsonAnySetter public void set(String name, Object value) { fruitPackage.put(name, value); } } |
Let’s dig deeper:
1) @JsonProperty : This annotation is used on a property or method. it provide mechanism for Serialization and Deserialization of JSON.
2) @JsonIgnoreProperties : This Class level annotation is used to ignore certain properties to be serialized & deserialized. It means that they will not be mapped to JSON content.
3) @JsonAnySetter, @JsonAnyGetter : Two annotations are applied on Getter/Setter methods working with a Map. @JsonAnySetter will catch JSON value which is not mapped to a property in POJO class and deserialized(stored) into Map.
These annotations works as a Catch-All and are applied on Getters/Setter working with a Map. If there is any JSON value which is not mapped to a property in POJO, then that value can be caught by @JsonAnySetter, and stored (deserialized) into Map. Similarly @JsonAnyGetter will serialized all values which are stored into Map back to JSON.
4) @JsonSerialize : This annotation is used to customize the default serialization (Java to JSON) process. In case the default serialization is not matching your needs and you should customize it for your requirement.
In this example, we only show the popular used annotations. You can refer to all annotations by referring to the JavaDocs
Create Custom Serializer
In this Jackson Json Annotation Example, Instead of showing default format of a property we can declare a Custom Serializer to serialize with desired format. Here, we create Customer Serializer and annotate it for importedDate property.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.javabycode.jackson; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; public class MyCustomDate extends JsonSerializer<Date> { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); @Override public void serialize(Date date, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException { String formattedDate = dateFormat.format(date); generator.writeString(formattedDate); } } |
Create Main
The main class is quite simple. We read from a file and deserialize the input JSON into a POJO object using ObjectMapper readValue. Then we serialize that POJO object using ObjectMapper writeValue and write the JSON data to a file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javabycode.jackson; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonJsonAnnotationExample { public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); Fruit fruit = mapper.readValue(new File("fruit.json"), Fruit.class); mapper.writeValue(new File("newFruit.json"), fruit); } } |
Running the above main class, the output file contains content like below(newFruit.json):
1 |
{"name":"Apple","produceby":["Indonesia","Combodia","Peru"],"importedDate":"08/23/2016","costPrice":0,"cost":0,"fruitPackage":{"name":"Fruit Punnets","quantityNet":5}} |
That’s it on the tutorial Jackson Json Annotation Example. If you find any error on this tutorial, please leave comment.
Download source code, click link below
Jackson-Json-Annotation-Example.zip