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.




Maven configuration



    4.0.0

    com.example
    writeGson
    jar
    2.0.1
    JSon example: Gson

    
        
            com.google.code.gson
            gson
            1.7.1
        
    



Java Bean


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 org.camelcode;

import com.google.gson.annotations.SerializedName;

public class Book {
    @SerializedName("custom_name") private String author;
    private String title;

    public Book(String author, String title) {
        this.author = author;
        this.title = title;
    }
}


Helper class


The following is an example of how to use both Gson naming policy features: 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 FieldNamingPolicy class for more information.


package org.camelcode;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class WriteGson {

    public static void main(String...args) {
        Book book = new Book("camelcode.org", "Gson custom naming");
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
        String jsonRepresentation = gson.toJson(book);
        System.out.println(jsonRepresentation);
    }
}


Output

{"custom_name":"camelcode.org","Title":"Gson custom naming"}


Download


Download source code - Custom-Json-Field-Naming-with-GSON.zip  2 KB

References