001package com.jeff_media.jsonconfigurationserialization; 002 003import com.google.gson.Gson; 004import com.google.gson.GsonBuilder; 005import com.google.gson.JsonDeserializer; 006import com.google.gson.JsonSerializer; 007import org.bukkit.configuration.serialization.ConfigurationSerializable; 008 009/** 010 * Utility class for serializing and deserializing ConfigurationSerializables to and from Json 011 */ 012public final class JsonConfigurationSerialization { 013 014 /** 015 * A {@link JsonSerializer} and {@link JsonDeserializer} for {@link ConfigurationSerializable}s to be used with {@link GsonBuilder#registerTypeHierarchyAdapter(Class, Object)} 016 */ 017 public static final ConfigurationSerializableTypeHierarchyAdapter TYPE_HIERARCHY_ADAPTER = new ConfigurationSerializableTypeHierarchyAdapter(); 018 019 private static final Gson GSON = new GsonBuilder() 020 .registerTypeHierarchyAdapter(ConfigurationSerializable.class, TYPE_HIERARCHY_ADAPTER) 021 .create(); 022 023 024 private JsonConfigurationSerialization() { 025 throw new IllegalStateException("Utility class"); 026 } 027 028 /** 029 * Serializes a ConfigurationSerializable to a Json String 030 * 031 * @param serializable ConfigurationSerializable to serialize 032 * @return Json String 033 */ 034 public static String serialize(ConfigurationSerializable serializable) { 035 return GSON.toJson(serializable, ConfigurationSerializable.class); 036 } 037 038 039 /** 040 * Deserializes a ConfigurationSerializable from a Json String 041 * 042 * @param json Json String 043 * @return deserialized ConfigurationSerializable 044 * @throws IllegalArgumentException if the Json String is invalid or if the ConfigurationSerializable class is not found 045 */ 046 public static ConfigurationSerializable deserialize(String json) throws IllegalArgumentException { 047 return GSON.fromJson(json, ConfigurationSerializable.class); 048 } 049 050 /** 051 * Deserializes a ConfigurationSerializable from a Json String 052 * 053 * @param json Json String 054 * @param clazz Class of the ConfigurationSerializable 055 * @return deserialized ConfigurationSerializable 056 * @throws IllegalArgumentException if the Json String is invalid or if the ConfigurationSerializable class is not found 057 * @throws ClassCastException if the ConfigurationSerializable is not of the specified class 058 */ 059 public static <T extends ConfigurationSerializable> T deserialize(String json, Class<T> clazz) throws IllegalArgumentException, ClassCastException { 060 return GSON.fromJson(json, clazz); 061 } 062 063 064}