Custom JSON field naming with Gson
- Read json file with GSON
- Write json file using GSON
- Exclude fields from JSON using Gson with @Expose
- Pretty printing JSON String with Gson
- Custom JSON field naming with Gson
- Serialize Object with null values using GSON
- Exclude fields from JSON with java modifiers using Gson
- Read json file with GSON
- Write json file using GSON
- From Java to JSON
- From JSON to Java
- From JSON to XML
- From XML to JSON
- Exclude fields from JSON using Gson with @Expose
- Pretty printing JSON String with Gson
- Custom JSON field naming with Gson
- Serialize Object with null values using GSON
- Exclude fields from JSON with java modifiers using Gson
Comments (0)
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
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"}





Latest Posts
Latest Comments
Tag cloud