package cn.citycraft.TellRaw.manual; import java.io.IOException; import java.io.StringWriter; import java.util.Map; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import cn.citycraft.GsonAgent.GsonAgent; import cn.citycraft.GsonAgent.api.stream.JsonWriter; import cn.citycraft.TellRaw.common.JsonRepresentedObject; /** * 序列化Item的类 * * @since 2015年12月14日 下午1:30:51 * @author 许凯 */ public class GItemStack implements JsonRepresentedObject { private final ItemStack item; private final String jsonString; protected GItemStack(final ItemStack item) { this.item = item.clone(); final StringWriter string = new StringWriter(); final JsonWriter json = GsonAgent.newJsonWriter(string); try { this.writeJson(json); json.close(); } catch (final IOException e) { throw new RuntimeException("invalid message:", e); } this.jsonString = string.toString(); } @Override public String toString() { return this.jsonString; } @Override public void writeJson(final JsonWriter json) throws IOException { try { json.beginObject(); json.nameWithoutQuotes("id").value(this.item.getTypeId()); json.nameWithoutQuotes("Damage").value(this.item.getDurability()); if (this.item.getAmount() > 1) { json.nameWithoutQuotes("Count").value(this.item.getAmount()); } if (this.item.hasItemMeta()) { json.nameWithoutQuotes("tag").beginObject(); final ItemMeta im = item.getItemMeta(); if (im.hasEnchants()) { json.nameWithoutQuotes("ench").beginArray(); for (final Map.Entry ench : im.getEnchants().entrySet()) { json.beginObject().nameWithoutQuotes("id").value(ench.getKey().getId()).nameWithoutQuotes("lvl").value(ench.getValue()).endObject(); } json.endArray(); } if (im.hasDisplayName() || im.hasLore()) { json.nameWithoutQuotes("display").beginObject(); if (im.hasDisplayName()) { json.nameWithoutQuotes("Name").value(im.getDisplayName()); } if (im.hasLore()) { json.nameWithoutQuotes("Lore").beginArray(); for (final String line : im.getLore()) { json.value(line); } json.endArray(); } json.endObject(); } json.endObject(); } json.endObject(); } catch (final IOException e) { Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e); } } }