Skip to content

Instantly share code, notes, and snippets.

@electrolobzik
Forked from hvisser/Example.java
Last active August 29, 2015 14:15
Show Gist options
  • Save electrolobzik/b842b92e46aad24c0c92 to your computer and use it in GitHub Desktop.
Save electrolobzik/b842b92e46aad24c0c92 to your computer and use it in GitHub Desktop.
// TypeToken is a Gson class
Type type = new TypeToken<List<Author>>(){}.getType();
GsonFieldConverterFactory factory = new GsonFieldConverterFactory(type);
// Register the factory and set the instance as the global Cupboard instance
CupboardFactory.setCupboard(new CupboardBuilder().registerFieldConverterFactory(factory).build());
import com.google.gson.Gson;
import android.content.ContentValues;
import android.database.Cursor;
import java.lang.reflect.Type;
import nl.qbusict.cupboard.convert.EntityConverter;
import nl.qbusict.cupboard.convert.FieldConverter;
public class GsonFieldConverter<T> implements FieldConverter<T> {
private final Gson mGson;
private final Type mType;
public GsonFieldConverter(Gson gson, Type type) {
mGson = gson;
mType = type;
}
@Override
public T fromCursorValue(Cursor cursor, int columnIndex) {
return mGson.fromJson(cursor.getString(columnIndex), mType);
}
@Override
public EntityConverter.ColumnType getColumnType() {
return EntityConverter.ColumnType.TEXT;
}
@Override
public void toContentValue(T value, String key, ContentValues values) {
values.put(key, mGson.toJson(value));
}
}
import com.google.gson.Gson;
import java.lang.reflect.Type;
import nl.qbusict.cupboard.Cupboard;
import nl.qbusict.cupboard.convert.FieldConverter;
import nl.qbusict.cupboard.convert.FieldConverterFactory;
public class GsonFieldConverterFactory implements FieldConverterFactory {
private Type mType;
private Gson mGson;
public GsonFieldConverterFactory(Gson gson, Type type) {
this.mGson = gson;
this.mType = type;
}
public GsonFieldConverterFactory(Type type) {
this.mType = type;
this.mGson = new Gson();
}
@Override
public FieldConverter<?> create(Cupboard cupboard, Type type) {
if (type == mType) {
return new GsonFieldConverter(mGson, type);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment