FieldNamingPolicy Example

In this post under Gson, I will show how to change the naming convention of field names when serialized to JSON format.

I will show how to change the naming convention from out of the box provided standard naming conventions.

Gson out of the box provides the below naming conventions as part of the enum com.google.gson.FieldNamingPolicy
1) IDENTITY
Using this naming policy with Gson will ensure that the field name is unchanged.

2) LOWER_CASE_WITH_DASHES
Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by a dash (-).

3) LOWER_CASE_WITH_DOTS
Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by a dot (.).

4) LOWER_CASE_WITH_UNDERSCORES
Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by an underscore (_).

5) UPPER_CAMEL_CASE
Using this naming policy with Gson will ensure that the first “letter” of the Java field name is capitalized when serialized to its JSON form.

6) UPPER_CAMEL_CASE_WITH_SPACES
Using this naming policy with Gson will ensure that the first “letter” of the Java field name is capitalized when serialized to its JSON form and the words will be separated by a space.

Below code shows how to change the existing naming convention to the one from the above.

Main Code


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

At line 12, we create an instance of GsonBuilder named ‘gsonBuilder’.

At line 13, we tell the gsonBuilder to create an instance of Gson which should use the FieldNamingPolicy.LOWER_CASE_WITH_DASHES as the new naming convention by calling setFieldNamingPolicy method on gsonBuilder.

In this way we can change the default naming convention

Output

{“f-name”:”fName”,”l-name”:”lName”,”age”:35}

Leave a Reply