Skip to content

Instantly share code, notes, and snippets.

@ViliusKraujutis
Created October 4, 2016 15:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ViliusKraujutis/ca2747c313b9025471b66218a10393ff to your computer and use it in GitHub Desktop.
Two different custom value enum serialization
...
Gson gson = new GsonBuilder()
.registerTypeAdapter(NumberOfPeople.class, NumberOfPeople.getDeserializer())
.create();
return new Retrofit.Builder()
...
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
package com.showaround.api.model;
import android.support.annotation.StringRes;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.showaround.R;
import java.lang.reflect.Type;
/**
* @author Vilius Kraujutis
* @since 2016-10-03 21:12.
*/
public enum NumberOfPeople {
just_me(1, R.string.number_of_people_1),
two_people(2, R.string.number_of_people_2),
three_people(3, R.string.number_of_people_3),
more_people(4, R.string.number_of_people_4);
int value;
@StringRes int label;
NumberOfPeople(int value, @StringRes int label) {
this.value = value;
this.label = label;
}
public static NumberOfPeople findByAbbr(int value) {
for (NumberOfPeople currEnum : NumberOfPeople.values()) {
if (currEnum.value == value) {
return currEnum;
}
}
return null;
}
public static Deserializer getDeserializer() {
return new Deserializer();
}
public int getValue() {
return value;
}
@StringRes
public int getLabel() {
return label;
}
private static class Deserializer implements
JsonDeserializer<NumberOfPeople>, JsonSerializer<NumberOfPeople> {
@Override
public NumberOfPeople deserialize(JsonElement json,
Type typeOfT, JsonDeserializationContext ctx)
throws JsonParseException {
int typeInt = json.getAsInt();
return NumberOfPeople
.findByAbbr(typeInt);
}
@Override
public JsonElement serialize(NumberOfPeople src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src.getValue());
}
}
}
package com.showaround.api.model;
import android.support.annotation.StringRes;
import com.google.gson.annotations.SerializedName;
import com.showaround.R;
/**
* @author Vilius Kraujutis
* @since 2016-10-03 21:12.
*/
public enum NumberOfPeople {
@SerializedName("1")
just_me(R.string.number_of_people_1),
@SerializedName("2")
two_people(R.string.number_of_people_2),
@SerializedName("3")
three_people(R.string.number_of_people_3),
@SerializedName("4")
more_people(R.string.number_of_people_4);
@StringRes int label;
NumberOfPeople(@StringRes int label) {
this.label = label;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment