Skip to content

Instantly share code, notes, and snippets.

@banasiak
Created April 6, 2016 01:01
Show Gist options
  • Save banasiak/c7f16e737f4336e2a3249f15697c1a1e to your computer and use it in GitHub Desktop.
Save banasiak/c7f16e737f4336e2a3249f15697c1a1e to your computer and use it in GitHub Desktop.
package com.banasiak.android.example.api.parser;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
/**
* All API responses are returned in the following format:
* {
* "data": {
* // HTTP 200 data object
* },
* "error": {
* // HTTP 4xx/5xx error object
* }
* }
* This custom Gson type adapter can be registered for generic response objects and handles
* deserializing the response into the appropriate object typing depending on the key specified in
* the constructor.
*
* @param <T> the class to deserialize the JSON string as
*/
public class RestDeserializer<T> implements JsonDeserializer<T> {
public static final String DATA = "data";
public static final String ERROR = "error";
private String key;
/**
* Custom Gson type adapter for deserializing JSON objects inside a REST data/error wrapper.
* @param key the key to deserialize (i.e. "data" or "error")
*/
public RestDeserializer(String key) {
this.key = key;
}
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException {
JsonElement content = je.getAsJsonObject().get(key);
return new Gson().fromJson(content, type);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment