Skip to content

Instantly share code, notes, and snippets.

@NightlyNexus
Created June 16, 2015 19:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NightlyNexus/10aedfd8afed0a0fcef2 to your computer and use it in GitHub Desktop.
Save NightlyNexus/10aedfd8afed0a0fcef2 to your computer and use it in GitHub Desktop.
Remove those pesky "status" objects in your JSON payload with Gson. Usage: new GsonConverter(new GsonBuilder().registerTypeAdapterFactory(new ItemTypeAdapterFactory())create());
public static class ItemTypeAdapterFactory implements TypeAdapterFactory {
final static String KEY_TO_REMOVE = "status";
@Override
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>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}
@Override
public T read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject.entrySet().size() == 2) {
jsonObject.remove(KEY_TO_REMOVE);
jsonElement = jsonObject.entrySet().iterator().next().getValue();
}
}
return delegate.fromJsonTree(jsonElement);
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment