Created
September 29, 2023 19:24
-
-
Save KeyKatyu/420add78bdf35754e6bc3aaeb5f9e73f to your computer and use it in GitHub Desktop.
Serialize ItemStack class to JSON
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
import com.google.gson.*; | |
import com.google.gson.reflect.TypeToken; | |
import fr.keykatyu.hordes.Main; | |
import org.bukkit.Bukkit; | |
import org.bukkit.configuration.serialization.ConfigurationSerializable; | |
import org.bukkit.inventory.ItemStack; | |
import org.bukkit.inventory.meta.ItemMeta; | |
import java.lang.reflect.Type; | |
import java.util.Map; | |
public class ItemStackAdapter implements JsonSerializer<ItemStack>, JsonDeserializer<ItemStack> { | |
@Override | |
public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { | |
Map<String, Object> map = Main.getGSON().fromJson(json, TypeToken.get(Map.class).getType()); | |
map.putIfAbsent("v", Bukkit.getUnsafe().getDataVersion()); | |
if(map.containsKey("meta")) { | |
Map<String, Object> meta = (Map<String, Object>) map.get("meta"); | |
ConfigurationSerializable deserializedMeta = context.deserialize(Main.getGSON().toJsonTree(meta), ConfigurationSerializable.class); | |
map.remove("meta"); | |
ItemStack is = ItemStack.deserialize(map); | |
is.setItemMeta((ItemMeta) deserializedMeta); | |
return is; | |
} else { | |
return ItemStack.deserialize(map); | |
} | |
} | |
@Override | |
public JsonElement serialize(ItemStack src, Type typeOfSrc, JsonSerializationContext context) { | |
Map<String, Object> map = src.serialize(); | |
map.putIfAbsent("v", Bukkit.getUnsafe().getDataVersion()); | |
if(src.hasItemMeta()) { | |
JsonElement meta = context.serialize(src.getItemMeta(), ConfigurationSerializable.class); | |
map.put("meta", meta.getAsJsonObject()); | |
} | |
return Main.getGSON().toJsonTree(map); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment