Posted on 2 mins read

When you develop an application, usually you will have to consume an API Service which might return some JSON data. You might not need all values from the JSON data.

The question is how do you process such data the right way?

Typically, you will retrieve the data using a HTTP client and then pass it on to a Object Relational Mapper. In my experience APIs return data based on models crafted for the database, however, for client side applications the model you design might be different from what the API returns you (due to application needs/ease of development). Hence, you need to extract part of it, transform it or map it differently.

If you happen to use GSON and retrofit 2… Perhaps this example will help you.

Sample json data:

{
  "date": "2016-01-01T21:23:00",
  "places": [
    {
      "id": 1,
      "amount": 25
    },
    {
      "id": 2,
      "amount": 59
    },
    {
      "id": 3,
      "amount": 28
    },
    {
      "id": 4,
      "amount": 11
    }
  ]
}

Lets say you just want the “list” of places.

First define a model for each “Place”.


private int id;
private int amount;

//Constructors, getters and setters

Define a custom deserializer for GSON with a main method for testing (or you could setup JUnit).

class CustomPlaceDeserializer<T> implements JsonDeserializer<List<T>> {

    public List<T> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
            throws JsonParseException {

        JsonElement results = jsonElement.getAsJsonObject().get("places");

        return new Gson().fromJson(results, type);
    }

    public static void main(String[] args) throws Exception {

        //

        // Configure Gson
        GsonBuilder gsonBuilder = new GsonBuilder();
        Type listType = new TypeToken<ArrayList<Place>>(){}.getType();
        gsonBuilder.registerTypeAdapter(listType, new CustomPlaceDeserializer<Place>());
        Gson gson = gsonBuilder.create();

        // The JSON data
        String jsonstring = "replace this with sample json string";

        // Parse JSON to Java
        List<Place> places = gson.fromJson(jsonstring, listType);
        System.out.println(places.size());
    }

}

If you are using retrofit 2, it might look something like this:

Gson customGson =
        new GsonBuilder()
                .registerTypeAdapter(listType, new CustomPlaceDeserializer<Place>())
                .create();