-
-
Notifications
You must be signed in to change notification settings - Fork 140
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Addd GSON enum type adapter for compatibility with Mohist
- Loading branch information
1 parent
e472e07
commit bedeb7c
Showing
2 changed files
with
65 additions
and
1 deletion.
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
61 changes: 61 additions & 0 deletions
61
src/main/java/world/bentobox/bentobox/database/json/adapters/EnumTypeAdapter.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,61 @@ | ||
package world.bentobox.bentobox.database.json.adapters; | ||
|
||
import java.io.IOException; | ||
import java.util.Arrays; | ||
|
||
import com.google.common.collect.BiMap; | ||
import com.google.common.collect.HashBiMap; | ||
import com.google.gson.TypeAdapter; | ||
import com.google.gson.annotations.SerializedName; | ||
import com.google.gson.stream.JsonReader; | ||
import com.google.gson.stream.JsonToken; | ||
import com.google.gson.stream.JsonWriter; | ||
|
||
|
||
/** | ||
* @author tastybento | ||
* | ||
* @param <T> enum class to be serialized | ||
*/ | ||
public final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> { | ||
|
||
|
||
/** | ||
* Bimap to store name <-> enum references | ||
*/ | ||
private final BiMap<String, T> enumMap = HashBiMap.create(); | ||
|
||
|
||
public EnumTypeAdapter(Class<T> enumClass) { | ||
for (T value : enumClass.getEnumConstants()) { | ||
|
||
String name = value.name(); | ||
try { | ||
SerializedName annotation = enumClass.getField(name).getAnnotation(SerializedName.class); | ||
|
||
if (annotation != null) { | ||
Arrays.stream(annotation.alternate()).forEach(s -> enumMap.put(s, value)); | ||
// Reset name | ||
name = annotation.value(); | ||
} | ||
|
||
} catch (NoSuchFieldException e) { | ||
// Ignore | ||
} | ||
|
||
enumMap.put(name, value); | ||
} | ||
} | ||
|
||
@Override public T read(JsonReader input) throws IOException { | ||
if (JsonToken.NULL.equals(input.peek())) { | ||
input.nextNull(); | ||
return null; | ||
} | ||
return enumMap.get(input.nextString()); | ||
} | ||
|
||
@Override public void write(JsonWriter output, T enumValue) throws IOException { | ||
output.value(enumValue != null ? enumMap.inverse().get(enumValue) : null); | ||
} | ||
} |