I solved this issue ... I had to make a TypeAdapterFactory
that set empty objects to null
then filtered out the nulls from the resulting list.
Here is my TypeAdapterFactory
private static class EmptyCheckTypeAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
// We filter out the EmptyCheckTypeAdapter as we need to check this for emptiness!
if (Story.class.isAssignableFrom(type.getRawType())) {
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
return new EmptyCheckTypeAdapter<>(delegate, elementAdapter).nullSafe();
}
return null;
}
public class EmptyCheckTypeAdapter<T> extends TypeAdapter<T> {
private final TypeAdapter<T> delegate;
private final TypeAdapter<JsonElement> elementAdapter;
public EmptyCheckTypeAdapter(final TypeAdapter<T> delegate,
final TypeAdapter<JsonElement> elementAdapter) {
this.delegate = delegate;
this.elementAdapter = elementAdapter;
}
@Override
public void write(final JsonWriter out, final T value) throws IOException {
this.delegate.write(out, value);
}
@Override
public T read(final JsonReader in) throws IOException {
final JsonObject asJsonObject = elementAdapter.read(in).getAsJsonObject();
if (asJsonObject.entrySet().isEmpty()) {
return null;
}
return this.delegate.fromJsonTree(asJsonObject);
}
}
}
Finally, filtered out the null
s using the following code
myDto.stories.removeAll(Collections.singleton(null));