Created
June 16, 2015 19:25
-
-
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());
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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