Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- import java.util.Map;
- import java.util.function.Consumer;
- import javax.annotation.Nullable;
- import org.bukkit.Material;
- import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack;
- import org.bukkit.entity.Player;
- import org.bukkit.inventory.ItemStack;
- import com.google.gson.Gson;
- import com.google.gson.JsonSyntaxException;
- import com.google.gson.reflect.TypeToken;
- import com.mojang.brigadier.exceptions.CommandSyntaxException;
- import net.minecraft.server.v1_13_R2.MojangsonParser;
- import net.minecraft.server.v1_13_R2.NBTTagCompound;
- public class ItemUtility {
- public static Map<String, Object> itemToMap(ItemStack item) {
- Map<String, Object> map = new HashMap<String, Object>();
- if (item == null) item = new ItemStack(Material.AIR);
- Material type = item.getType();
- int count = item.getAmount();
- NBTTagCompound tag = CraftItemStack.asNMSCopy(item).getTag();
- map.put("type", type);
- map.put("count", count);
- if (tag != null) map.put("tag", tag.asString());
- return map;
- }
- public static String itemToString(ItemStack item) {
- return new Gson().toJson(itemToMap(item));
- }
- public static ItemStack itemFromMap(Map<String, Object> map) throws CommandSyntaxException {
- Material type = Material.valueOf((String) map.get("type"));
- int count = ((Double) map.get("count")).intValue();
- String tagRaw = (String) map.get("tag");
- NBTTagCompound tag = tagRaw != null? MojangsonParser.parse(tagRaw): null;
- ItemStack item = new ItemStack(type, count);
- if (tag != null) {
- net.minecraft.server.v1_13_R2.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
- nmsStack.setTag(tag);
- item.setItemMeta(CraftItemStack.asBukkitCopy(nmsStack).getItemMeta());
- }
- return item;
- }
- @SuppressWarnings("unchecked")
- public static ItemStack itemFromString(String str) throws JsonSyntaxException, CommandSyntaxException {
- return itemFromMap((Map<String, Object>) new Gson().fromJson(str, new TypeToken<Map<String, Object>>() {}.getType()));
- }
- public static void editTag(ItemStack item, Consumer<NBTTagCompound> consumer) {
- net.minecraft.server.v1_13_R2.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
- consumer.accept(nmsStack.getOrCreateTag());
- item.setItemMeta(CraftItemStack.asBukkitCopy(nmsStack).getItemMeta());
- }
- public static NBTTagCompound getTag(ItemStack item) {
- return CraftItemStack.asNMSCopy(item).getTag();
- }
- public static String toCommand(ItemStack item, @Nullable Player player) {
- return "/give " + (player == null? "@p" : player.getName()) + " minecraft:" + item.getType().toString().toLowerCase()
- + tagToString(item) + ' ' + item.getAmount();
- }
- public static String tagToString(ItemStack item) {
- return CraftItemStack.asNMSCopy(item).getOrCreateTag().asString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement