GSON tip: @JsonProperty equivalent

Jackson has a very useful annotation @JsonProperty that gives developer the option to provide a name that will be used to map data from JSON to the value object. This is very useful when REST API you are interacting with does not follow conventions like some fields are caps, some camel case, and other using underscore. Today, I had a similar need but I was working with GSON library instead of Jackson. The solution in Gson is a similar annotation called @SerializedName that you can use to provide names that match the source JSON. A simple example is shown below.

public class Message{
    @SerializedName("ID")
    private String id;
    @SerializedName("NFd")
    private int fileDescriptors;
}

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);