Skip to content

Instantly share code, notes, and snippets.

@francofabio
Last active October 18, 2015 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save francofabio/39067487c8ae71713cb3 to your computer and use it in GitHub Desktop.
Save francofabio/39067487c8ae71713cb3 to your computer and use it in GitHub Desktop.
vraptor4 gson enum serialization
public interface EnumDescribable {
String getDescription();
}
import java.lang.reflect.Type;
import javax.enterprise.context.Dependent;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
@Dependent
public class EnumDescribableConverter implements JsonDeserializer<EnumDescribable>, JsonSerializer<EnumDescribable> {
@SuppressWarnings("rawtypes")
@Override
public JsonElement serialize(EnumDescribable src, Type typeOfSrc, JsonSerializationContext context) {
Class<?> classOfSrc = (Class<?>) typeOfSrc;
if (!classOfSrc.isEnum()) {
throw new IllegalArgumentException("Expected an enum type");
}
if (src != null) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", ((Enum) src).name());
jsonObject.addProperty("description", src.getDescription());
return jsonObject;
}
return null;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public EnumDescribable deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (!((Class) typeOfT).isEnum()) {
throw new IllegalArgumentException("Expected an enum type");
}
Class<? extends Enum> classOfT = (Class<? extends Enum>) typeOfT;
if (json != null && !json.isJsonNull()) {
if (json.isJsonPrimitive()) {
return (EnumDescribable) Enum.valueOf(classOfT, json.getAsString());
} else {
JsonObject jsonObject = (JsonObject) json;
JsonElement value = jsonObject.get("name");
if (value != null) {
return (EnumDescribable) Enum.valueOf(classOfT, value.getAsString());
}
}
}
return null;
}
}
public enum Genre implements EnumDescribable {
MALE("Male"), FEMALE("Female");
private final String description;
Genre(String description) {
this.description = description;
}
@Override
public String getDescription() {
return description;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment