FieldNamingStrategy Example

In my previous post “FieldNamingPolicy Example”, I explained with an example how to change the naming convention using out of the box provided standard naming conventions.

In this post, I will explain with an example how to create your own custom naming conventions and configure the Gson to use it.

To create our own custom naming convention we need to create a class say “CustomFieldNamingStrategy” which implements the interface “com.google.gson.FieldNamingStrategy” as shown below

CustomFieldNamingStrategy class


import java.lang.reflect.Field;

import com.google.gson.FieldNamingStrategy;

public class CustomFieldNamingStrategy implements FieldNamingStrategy {
    @Override
    public String translateName(Field field) {
        return "pre_" + field.getName();
    }
}

As shown in the above code CustomFieldNamingStrategy implements the interface “com.google.gson.FieldNamingStrategy” and provide implementation to the method “translateName”.

The translateName method will prefix every field name (to be serialized) with the string “pre_”.

Next we will show how to configure the Gson to use the CustomFieldNamingStrategy.

Below is the main code

Main class


1  import com.google.gson.Gson;
2  import com.google.gson.GsonBuilder;
3  
4  public class GsonDemo9 {
5   public static void main(String[] args) {
6       Person person = new Person();
7       person.setAge(35);
8       person.setfName("fName");
9       person.setlName("lName");
10      
11      CustomFieldNamingStrategy customFieldNamingStrategy = new CustomFieldNamingStrategy();
12      
13      GsonBuilder gsonBuilder = new GsonBuilder();
14      Gson gson = gsonBuilder.setFieldNamingStrategy(customFieldNamingStrategy).create();
15      String result = gson.toJson(person);
16      System.out.println(result);
17  }
18 }

In the above code, at line 11, I create an instance of CustomFieldNamingStrategy.

At line 13, I create an instance of GsonBuilder named “gsonBuilder”.

At line 14, I tell the gsonBuilder to create an instance of Gson class which should use “customFieldNamingStrategy” (when serializing field names of an objects) by calling “setFieldNamingStrategy” method.

Output

{“pre_fName”:”fName”,”pre_lName”:”lName”,”pre_age”:35}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s