Skip to content

Instantly share code, notes, and snippets.

@bulwinkel
Last active January 24, 2017 02:37
Show Gist options
  • Save bulwinkel/51ee6c315dbc9a35396dbf152635fb73 to your computer and use it in GitHub Desktop.
Save bulwinkel/51ee6c315dbc9a35396dbf152635fb73 to your computer and use it in GitHub Desktop.
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 io.realm.RealmList;
import io.realm.RealmModel;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Set;
public class RealmListJsonAdapter<T extends RealmModel> extends JsonAdapter<RealmList<T>> {
public static final JsonAdapter.Factory FACTORY = new JsonAdapter.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 == RealmList.class) {
return newRealmListAdapter(type, moshi).nullSafe();
}
return null;
}
};
private final JsonAdapter<T> elementAdapter;
public RealmListJsonAdapter(JsonAdapter<T> elementAdapter) {
this.elementAdapter = elementAdapter;
}
RealmList<T> newRealmList() {
return new RealmList<T>();
}
private static <T extends RealmModel> JsonAdapter<RealmList<T>> newRealmListAdapter(Type type, Moshi moshi) {
Type elementType = Types.collectionElementType(type, Collection.class);
JsonAdapter<T> elementAdapter = moshi.adapter(elementType);
return new RealmListJsonAdapter<T>(elementAdapter);
}
@Override public RealmList<T> fromJson(JsonReader reader) throws IOException {
RealmList<T> result = newRealmList();
reader.beginArray();
while (reader.hasNext()) {
result.add(elementAdapter.fromJson(reader));
}
reader.endArray();
return result;
}
@Override public void toJson(JsonWriter writer, RealmList<T> value) throws IOException {
writer.beginArray();
for (T element : value) {
elementAdapter.toJson(writer, element);
}
writer.endArray();
}
@Override public String toString() {
return elementAdapter + ".realmList()";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment