-
Notifications
You must be signed in to change notification settings - Fork 157
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use type adapter to make enums lowercase
- Loading branch information
1 parent
faea3fd
commit c4c66c2
Showing
3 changed files
with
107 additions
and
45 deletions.
There are no files selected for viewing
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
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
45 changes: 45 additions & 0 deletions
45
src/main/java/com/terraformersmc/modmenu/util/EnumToLowerCaseJsonConverter.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package com.terraformersmc.modmenu.util; | ||
|
||
import com.google.gson.*; | ||
|
||
import java.lang.reflect.Type; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
public final class EnumToLowerCaseJsonConverter implements JsonSerializer<Enum<?>>, JsonDeserializer<Enum<?>> { | ||
private static final Map<String, Class<? extends Enum<?>>> TYPE_CACHE = new HashMap<>(); | ||
|
||
@Override | ||
public JsonElement serialize(final Enum<?> src, final Type typeOfSrc, final JsonSerializationContext context) { | ||
if (src == null) { | ||
return JsonNull.INSTANCE; | ||
} | ||
return new JsonPrimitive(src.name().toLowerCase()); | ||
} | ||
|
||
@Override | ||
public Enum<?> deserialize(final JsonElement json, | ||
final Type type, | ||
final JsonDeserializationContext context) throws JsonParseException { | ||
if (json == null || json.isJsonNull()) { | ||
return null; | ||
} | ||
|
||
if (!json.isJsonPrimitive() || !json.getAsJsonPrimitive().isString()) { | ||
throw new JsonParseException("Expecting a String JsonPrimitive, getting " + json); | ||
} | ||
|
||
try { | ||
final String enumClassName = type.getTypeName(); | ||
Class<? extends Enum<?>> enumClass = TYPE_CACHE.get(enumClassName); | ||
if (enumClass == null) { | ||
enumClass = (Class<? extends Enum<?>>) Class.forName(enumClassName); | ||
TYPE_CACHE.put(enumClassName, enumClass); | ||
} | ||
|
||
return Enum.valueOf((Class) enumClass, json.getAsString().toUpperCase()); | ||
} catch (final ClassNotFoundException e) { | ||
throw new JsonParseException(e); | ||
} | ||
} | ||
} |