-
Notifications
You must be signed in to change notification settings - Fork 43
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Split up JSON and other serialization code
- Loading branch information
Showing
2 changed files
with
61 additions
and
42 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
54 changes: 54 additions & 0 deletions
54
platforms/common/src/main/java/dynamic_fps/impl/util/JsonUtil.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,54 @@ | ||
package dynamic_fps.impl.util; | ||
|
||
import com.google.gson.*; | ||
|
||
import java.lang.reflect.Type; | ||
import java.util.Locale; | ||
|
||
public class JsonUtil { | ||
private static final Gson GSON = new GsonBuilder() | ||
.setLenient() | ||
.serializeNulls() | ||
.setPrettyPrinting() | ||
.enableComplexMapKeySerialization() | ||
.registerTypeHierarchyAdapter(Enum.class, new EnumSerializer<>()) | ||
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) | ||
.create(); | ||
|
||
public static String toJson(Object object) { | ||
return GSON.toJson(object); | ||
} | ||
|
||
public static String toJson(JsonElement element) { | ||
return GSON.toJson(element); | ||
} | ||
|
||
public static JsonElement toJsonTree(Object object) { | ||
return GSON.toJsonTree(object); | ||
} | ||
|
||
public static <T> T fromJson(String data, Class<T> type) { | ||
return GSON.fromJson(data, type); | ||
} | ||
|
||
public static <T> T fromJson(JsonElement data, Class<T> type) { | ||
return GSON.fromJson(data, type); | ||
} | ||
|
||
private static final class EnumSerializer<T extends Enum<T>> implements JsonSerializer<T>, JsonDeserializer<T> { | ||
@Override | ||
public JsonElement serialize(T instance, Type type, JsonSerializationContext context) { | ||
return new JsonPrimitive(instance.toString().toLowerCase(Locale.ROOT)); | ||
} | ||
|
||
@Override | ||
public T deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { | ||
try { | ||
Class<T> class_ = (Class<T>) Class.forName(type.getTypeName()); | ||
return Enum.valueOf(class_, element.getAsString().toUpperCase(Locale.ROOT)); | ||
} catch (ClassNotFoundException | IllegalArgumentException e) { | ||
throw new JsonParseException(e); | ||
} | ||
} | ||
} | ||
} |