Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generic deserializers with Retrofit & rxJava
public abstract class Deserializer<T> implements JsonDeserializer<T> {
public abstract Class<T> setDestinationClass();
@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Log.d("Deserializer", "deserialize json: " + json);
return new Gson().fromJson(json, setDestinationClass());
}
}
public class FastAdapter<T> {
private RestAdapter adapter;
public PokeApi createPokeApi() {
return adapter.create(PokeApi.class);
}
public FastAdapter(String endpoint, final Class<T> klazz) {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(klazz, new Deserializer<T>() {
@Override
public Class<T> setDestinationClass() {
return klazz;
}
});
Gson gson = builder.create();
GsonConverter converter = new GsonConverter(gson);
adapter = new RestAdapter.Builder()
.setEndpoint(endpoint)
.setConverter(converter)
.build();
}
public PokeApi getPokedexService() {
return adapter.create(PokeApi.class);
}
}
public abstract class ListDeserializer<T> implements JsonDeserializer<List<T>> {
public abstract Class<T> setDestinationClass();
@Override
public List<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Log.d("ListDeserializer", "deserialize json: " + json);
List<T> list = new ArrayList<>();
JsonArray favouritesArray = json.getAsJsonArray();
for (JsonElement nextFavourieAddress : favouritesArray)
list.add((T) context.deserialize(nextFavourieAddress, setDestinationClass()));
return list;
}
}
public class Main{
public static final String TAG = Main.class.getSimpleName();
public static void main(String[] args){
final FastAdapter<PokeMove> adapter = new FastAdapter<>(PokeApi.POKEMON_API_ENDPOINT, PokeMove.class);
adapter.getPokedexService().getPokemonMove(1).subscribe(new Subscriber<PokeMove>() {
@Override
public void onCompleted() {
Log.d(TAG, "onCompleted ");
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "onError ");
}
@Override
public void onNext(PokeMove pokeMove) {
Log.d(TAG, "onNext pokeMove: " + pokeMove);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment