Skip to content

Instantly share code, notes, and snippets.

@baleen37
Created July 9, 2015 07:46
Show Gist options
  • Save baleen37/87a5fceb7be8a9f3698f to your computer and use it in GitHub Desktop.
Save baleen37/87a5fceb7be8a9f3698f to your computer and use it in GitHub Desktop.
retro fit item type adapter factory
public class ItemTypeAdapterFactory implements TypeAdapterFactory {
public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
return new TypeAdapter<T>() {
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}
public T read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject.has("data") && jsonObject.get("data").isJsonObject())
{
jsonElement = jsonObject.get("data");
}
}
return delegate.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment