Gson Annotations Example shows you some useful annotations that are provided by Google Gson, for example: @Expose, @SerializedName, @Since, @Until, and @JsonAdapter. With these annotations, we can customize the serialization of java object to JSON or desirialization of object from JSON.
Other interesting posts you may like
Table of contents:
1. Project structure
2. Maven Dependency
3. Create POJO with GSON annotations
4. Create Main class using @Expose for serialization/deserialization
5. Create Main class using Version for serialization/deserialization
Project structure
We are creating project with structure like below:
Maven Dependency
We will use the latest GSON version in this GSON Annotations Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?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>Gson-Annotation-Example</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Gson-Annotation-Example - ${project.artifactId}</name> <packaging>jar</packaging> <dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.2</version> </dependency> </dependencies> </project> |
Create POJO with GSON annotations
We create java class with GSON annotaions like 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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
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.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Since; import com.google.gson.annotations.Until; public class Fruit { @Expose private String name; @SerializedName("costPrice") @Expose(deserialize = false) private long cost; @Until(1.9) @Expose private Date importedDate; @Expose(serialize = false, deserialize = false) private String flavor; @Until(2.1) @Expose private List<String> produceby = new ArrayList<String>(); @Since(2.1) @Expose private Map<String, Object> fruitPackage = new HashMap<String, Object>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public long getCost() { return cost; } public void setCost(long cost) { this.cost = cost; } public List<String> getProduceby() { return produceby; } public void setProduceby(List<String> produceby) { this.produceby = produceby; } public Date getImportedDate() { return importedDate; } public void setImportedDate(Date importedDate) { this.importedDate = importedDate; } public String getFlavor() { return flavor; } public void setFlavor(String flavor) { this.flavor = flavor; } public Map<String, Object> getFruitPackage() { return fruitPackage; } public void setFruitPackage(Map<String, Object> fruitPackage) { this.fruitPackage = fruitPackage; } @Override public String toString() { return "Fruit [name=" + name + ", cost=" + cost + ", importedDate=" + importedDate + ", flavor=" + flavor + ", produceby=" + produceby + ", fruitPackage=" + fruitPackage + "]"; } } |
Let’s dig deeper:
@Expose: this annotation is used to serialize/deserialize a field. This annotation has no effect unless you build Gson with a GsonBuilder and invoke GsonBuilder.excludeFieldsWithoutExposeAnnotation() method.
@SerializedName: this annotation is used to serialize a field with different name instead of using actual field name.
Gson Custom Serialization
Sometimes, we need to customize behavior of default serialization/deserialization for our specified requirement. We can do this by writing custom JsonSerializer and JsonDeserializer implementation and registering them with GsonBuilder.
In this Gson Annotations Example, we will customize the importedDate field. We create the MySerializerDate class for serialization like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.javabycode.jackson; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.Date; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class MySerializerDate implements JsonSerializer<Date> { private static final SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(format.format(date)); } } |
and the MyDeserializerDate for deserialization like below:
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.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; public class MyDeserializerDate implements JsonDeserializer<Date> { private static final SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); public Date deserialize(JsonElement dateStr, Type typeOfSrc, JsonDeserializationContext context) { try { return format.parse(dateStr.getAsString()); } catch (ParseException e) { e.printStackTrace(); } return null; } } |
Create Main class using @Expose for serialization/deserialization
We create main class to see how two above annotations work, it looks like 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 |
package com.javabycode.jackson; import java.util.Date; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonExposeAnnotationExample { public static void main(String args[]) { GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting(); /* Register serializer and deserializer with GsonBuilder */ builder.registerTypeAdapter(Date.class, new MySerializerDate()); builder.registerTypeAdapter(Date.class, new MyDeserializerDate()); Gson gson = builder.create(); Fruit fruit = new Fruit(); fruit.setName("Banana"); fruit.setCost(10); fruit.setFlavor(""); fruit.setImportedDate(new Date()); fruit.getProduceby().add("Indonesia"); fruit.getProduceby().add("Canada"); fruit.getProduceby().add("Cuba"); fruit.getFruitPackage().put("package", "Fruit Punnets"); fruit.getFruitPackage().put("quantityNet", 5); /* Serialization */ System.out.println("Before serializing JSON string using GSON annotation"); System.out.println(fruit); System.out.println("After serializing JSON string using GSON annotation"); String serializedJson = gson.toJson(fruit); System.out.println(serializedJson); /* Deserialization */ System.out.println("Deserializing JSON string using GSON annotation"); Fruit newFruit = gson.fromJson(serializedJson, Fruit.class); System.out.println(newFruit); } } |
Run the above main on Eclipse, we will get the output like screen shot:
@Since: this annotation is used to manage versioning of Json classes. We can serialize/deserialize a field based on its certain version. @Since annotation and version number indicate a field that we can only serialize/deserialize that field starting that version number. Otherwise, before that version, it will ignored.
@Until: this annotation is used to manage versioning of Json classes. We can serialize/deserialize a field based on its certain version. @Util annotation and version number indicate a field that we can only serialize/deserialize that field util certain version. Otherwise, after that version, it will ignored.
Create Main class using Version for serialization/deserialization
Here, We create other main class for serialization/deserialization using version. Simply, we just set version number to GSON builder object like 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 |
package com.javabycode.jackson; import java.util.Date; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonSinceUtilAnnotationExample { public static void main(String args[]) { GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting(); /* Register serializer and deserializer with GsonBuilder */ builder.registerTypeAdapter(Date.class, new MySerializerDate()); builder.registerTypeAdapter(Date.class, new MyDeserializerDate()); Gson gson = builder.setVersion(2.0).create(); Fruit fruit = new Fruit(); fruit.setName("Banana"); fruit.setCost(10); fruit.setFlavor(""); fruit.setImportedDate(new Date()); fruit.getProduceby().add("Indonesia"); fruit.getProduceby().add("Canada"); fruit.getProduceby().add("Cuba"); fruit.getFruitPackage().put("package", "Fruit Punnets"); fruit.getFruitPackage().put("quantityNet", 5); /* Serialization */ System.out.println("Before serializing JSON string using GSON annotation"); System.out.println(fruit); System.out.println("After serializing JSON string using GSON annotation"); String serializedJson = gson.toJson(fruit); System.out.println(serializedJson); /* Deserialization */ System.out.println("Deserializing JSON string using GSON annotation"); Fruit newFruit = gson.fromJson(serializedJson, Fruit.class); System.out.println(newFruit); } } |
Running the above main we will get the output like below:
That’s all. Now You can create your own Gson Annotations Example by following all the above steps.
Download source code, click link below
Gson-Annotation-Example.zip