Custom JSON field naming using GSON
Gson supports custom naming for JSON fields. You can annotate your fields with @SerializedName
to provide this functionality. If there is an error in the naming of the field, it’ll throw a Runtime exception. In this tutorial we will show you how you can change the name of a field inside your Java Class.
Maven dependencies
<?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.memorynotfound.json.gson</groupId>
<artifactId>custom-namet</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<gson.version>2.3.1</gson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
</dependencies>
</project>
Object to be Serialised/Deserialised
Gson has special annotations that you can define on a per field basis. If an invalid field name is provided it could produce a “Runtime” excepetion.
package com.memorynotfound.json;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
public class Product {
private long id;
@SerializedName("item")
private String name;
private Date created;
private double amount;
public Product(long id, String name, Date created, double amount) {
this.id = id;
this.name = name;
this.created = created;
this.amount = amount;
}
}
Custom JSON field naming using GSON
The following is an example of how to use both Gson naming policy feature and custom naming.: Gson supports a couple of pre-defined field naming policies to convert the standard Java field names.
FieldNamingPolicy.UPPER_CAMEL_CASE
FieldNamingPolicy.LOWER_CASE_WITH_DASHES
FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES
FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES
See the GSON FieldNamingPolicy JavaDoc for more information.
package com.memorynotfound.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Date;
public class CustomNameGson {
public static void main(String... args){
Product product = new Product(1, "Playstation 4", new Date(), 499.99);
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String result = gson.toJson(product);
System.out.println(result);
}
}
Output
{"Id":1,"item":"Playstation 4","Created":"Dec 26, 2014 3:00:01 PM","Amount":499.99}