Skip to content

Instantly share code, notes, and snippets.

@steffandroid
Created June 9, 2016 02:31
Show Gist options
  • Save steffandroid/069dfe803bb2450a862789172d8c815e to your computer and use it in GitHub Desktop.
Save steffandroid/069dfe803bb2450a862789172d8c815e to your computer and use it in GitHub Desktop.
A Moshi type adapter factory for Guava's ImmutableList
import com.google.common.collect.ImmutableList;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.JsonReader;
import com.squareup.moshi.JsonWriter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class ImmutableListAdapter<T> extends JsonAdapter<ImmutableList<T>> {
public static final Factory FACTORY = new Factory() {
@Override
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
Class<?> rawType = Types.getRawType(type);
if (!annotations.isEmpty()) return null;
if (rawType == ImmutableList.class) {
return newImmutableListAdapter(type, moshi).nullSafe();
}
return null;
}
};
private final JsonAdapter<T> elementAdapter;
private ImmutableListAdapter(JsonAdapter<T> elementAdapter) {
this.elementAdapter = elementAdapter;
}
static <T> JsonAdapter<ImmutableList<T>> newImmutableListAdapter(Type type, Moshi moshi) {
Type elementType = Types.collectionElementType(type, ImmutableList.class);
JsonAdapter<T> elementAdapter = moshi.adapter(elementType);
return new ImmutableListAdapter<>(elementAdapter);
}
@Override
public ImmutableList<T> fromJson(JsonReader reader) throws IOException {
List<T> result = new ArrayList<>();
reader.beginArray();
while (reader.hasNext()) {
result.add(elementAdapter.fromJson(reader));
}
reader.endArray();
return ImmutableList.copyOf(result);
}
@Override
public void toJson(JsonWriter writer, ImmutableList<T> value) throws IOException {
writer.beginArray();
for (T element : value) {
elementAdapter.toJson(writer, element);
}
writer.endArray();
}
}
@gaara87
Copy link

gaara87 commented Mar 10, 2023

For anyone looking for a newer kotlin and moshi versions - https://gist.github.com/gaara87/158fb0dd5d503d7ac69c1d236a3f554b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment