Here’s a little quick tip about something that I think is a less well-known feature of Google’s awesome GSON library:

Parsing Java enums using annotations

Assuming you receive a simple JSON response like this:

{
    "value": 9,
    "suit": "hearts"
}

where suit is always a lower-case String of the following fixed set: hearts - diamonds - clubs - spades

The equivalent POJO would look something like this:

public class Card {
	private int value;
    private Suit suit;

    public int getValue() {
    	return value;
    }

    public Suit getSuit() {
    	return suit;
    }

    public enum Suit {
    	HEARTS,
        DIAMONDS,
        CLUBS,
        SPADES
    }
}

So what’s the simplest way of deserializing the suit field into the Java object? A common approach is to create a type adapter (e.g. LowercaseEnumTypeAdapterFactory) that will write the enum names in lower-case and map it to the correct constant.

However, there’s an easier way to do it, using annotations! GSON provides five different annotations, as documented in the Java Doc. The one we’re interested in is called SerializedName.

So let’s annotate our enum constants:

public class Card {
	private int value;
    private Suit suit;

    public int getValue() {
    	return value;
    }

    public Suit getSuit() {
    	if(suit == null) suit = Suit.UNKNOWN;
    	return suit;
    }

    public enum Suit {
    	@SerializedName("hearts") HEARTS,
        @SerializedName("diamonds") DIAMONDS,
        @SerializedName("clubs") CLUBS,
        @SerializedName("spades") SPADES,
        UNKNOWN
    }
}

Note that I also added another constant to the enum called UNKNOWN. The reason being that if your server returns (for whatever reason) a value that isn’t part of your enum set, we’ll return Suit.UNKNOWN in order to avoid a NullPointerException.

On the downside, this approach is case-sensitive. While solutions like the aforementioned LowercaseEnumTypeAdapterFactory are more flexible because of their case-insensitivity, they usually require more code to be written and need to be registered with a GsonBuilder. However, most of the time you should know what the response of the server you’re talking to looks like, so the annotation-based approach is generally the simpler and more concise solution.