Skip to content

Instantly share code, notes, and snippets.

@negativems
Last active June 13, 2019 21:08
Show Gist options
  • Save negativems/e0882a8e326251f5a303c1e7e4707e9d to your computer and use it in GitHub Desktop.
Save negativems/e0882a8e326251f5a303c1e7e4707e9d to your computer and use it in GitHub Desktop.
private static JsonObject itemToJson(ItemStack item, boolean useIndex, int index) {
if(item == null) return null;
Gson gson = new GsonBuilder().create();
// Map<String, Object> values = new LinkedHashMap<>();
JsonObject values = new JsonObject();
//Set data to variables
int id = item.getTypeId();
int amount = item.getAmount();
int data = item.getDurability();
int repairPenalty = 0;
boolean hasMeta = item.hasItemMeta();
String name = null, enchants = null;
List<String> lore = null;
Material mat = item.getType();
JsonObject bookMeta = null, armorMeta = null, skullMeta = null, fwMeta = null;
if(mat == Material.BOOK_AND_QUILL || mat == Material.WRITTEN_BOOK) bookMeta = BookSerialization.serializeBookMeta((BookMeta) item.getItemMeta());
else if(mat == Material.ENCHANTED_BOOK) bookMeta = BookSerialization.serializeEnchantedBookMeta((EnchantmentStorageMeta) item.getItemMeta());
else if(Util.isLeatherArmor(mat)) armorMeta = LeatherArmorSerialization.serializeArmor((LeatherArmorMeta) item.getItemMeta());
else if(mat == Material.SKULL_ITEM) skullMeta = SkullSerialization.serializeSkull((SkullMeta) item.getItemMeta());
else if(mat == Material.FIREWORK) fwMeta = FireworkSerialization.serializeFireworkMeta((FireworkMeta) item.getItemMeta());
if(hasMeta) {
ItemMeta meta = item.getItemMeta();
if(meta.hasDisplayName()) name = meta.getDisplayName();
if(meta.hasLore()) lore = meta.getLore();
if(meta.hasEnchants()) enchants = EnchantmentSerialization.serializeEnchantments(meta.getEnchants());
if(meta instanceof Repairable && ((Repairable) meta).hasRepairCost()) repairPenalty = ((Repairable) meta).getRepairCost();
}
//Add variables to the JsonObject
values.addProperty("id", id);
values.addProperty("amount", amount);
values.addProperty("data", data);
if(useIndex) values.addProperty("index", index);
if(name != null) values.addProperty("name", name);
if(enchants != null) values.addProperty("enchantments", enchants);
if(lore != null) values.add("lore", new JsonObject().getAsJsonArray(gson.toJson(lore)));
if(repairPenalty != 0) values.addProperty("repairPenalty", repairPenalty);
if(bookMeta != null && bookMeta.getAsJsonArray().size() > 0) values.add("book-meta", bookMeta);
if(armorMeta != null && armorMeta.getAsJsonArray().size() > 0) values.add("armor-meta", armorMeta);
if(skullMeta != null && skullMeta.getAsJsonArray().size() > 0) values.add("skull-meta", skullMeta);
if(fwMeta != null && fwMeta.getAsJsonArray().size() > 0) values.add("firework-meta", fwMeta);
return values;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment