Gson Tip: Using a different FieldNamingPolicy


Today, while write a client for a REST API I had the need to use a different field naming strategy than the default one. By default, when Gson tries to convert a JSON String to an object it expects field names in JSON to be same as field name in the converting object. For example, you can convert following JSON String to Message object as shown below.

{
"message": "hello world!"
}
public class Message{
private String message;
// setters and getters
}

To convert to message JSON to Message object you can use following code.

// String json
Message message = new Gson().fromJson(json, Message.class);

This will not work if JSON has different naming policy(first letter upper case) as shown below.

{
"Message": "hello world!"
}

To make it work, you can use GsonBuilder to create Gson with UPPER_CAMEL_CASE as field naming policy. This is shown below.

Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
Message message = gson.fromJson(json, Message.class);

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s