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=""




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 java.util.Date;

public class Product {

    private long id;
    private String name;
    private Date created;
    private double amount;

    public Product(long id, String name, Date created, double amount) { = id; = 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

See the GSON FieldNamingPolicy JavaDoc for more information.

package com.memorynotfound.json;


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);


{"Id":1,"item":"Playstation 4","Created":"Dec 26, 2014 3:00:01 PM","Amount":499.99}


You may also like...