public enum MyEnum {
ONE, TWO;
}
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyEnum.class, new GsonEnumByOrdinalSerializer<>())
.create();
Created
June 15, 2018 12:11
-
-
Save seeekr/714285026d4544470281648c521a608b to your computer and use it in GitHub Desktop.
de-/serialize enums by ordinal with GSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.denisandrejew.util; | |
import com.google.gson.*; | |
import lombok.experimental.var; // if java < 10 | |
import java.lang.reflect.Type; | |
public class GsonEnumByOrdinalSerializer<T extends Enum> implements JsonSerializer<T>, JsonDeserializer<T> { | |
@Override | |
public T deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { | |
try { | |
var cls = Class.forName(type.getTypeName()); | |
var types = cls.getEnumConstants(); | |
var ord = jsonElement.getAsInt(); | |
return ord <= types.length && ord >= 1 ? (T) types[ord - 1] : null; | |
} catch (ClassNotFoundException e) { | |
throw new RuntimeException(e); // fancy error handling here | |
} | |
} | |
@Override | |
public JsonElement serialize(T item, Type type, JsonSerializationContext jsonSerializationContext) { | |
return item == null ? JsonNull.INSTANCE : new JsonPrimitive(item.ordinal()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment