package dmillerw.menu.data.json;

import com.google.gson.*;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;

import javax.annotation.Nonnull;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * @author dmillerw
 */
public class ItemStackSerializer implements JsonSerializer<ItemStack>, JsonDeserializer<ItemStack> {

    @Override
    public JsonElement serialize(ItemStack src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject object = new JsonObject();

        object.add("name", new JsonPrimitive(String.valueOf(Item.REGISTRY.getNameForObject(src.getItem()))));
        object.add("damage", new JsonPrimitive(src.getItemDamage()));

        return object;
    }

    @Override
    @Nonnull
    public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (!json.isJsonObject()) {
            return ItemStack.EMPTY;
        }

        String name = "";
        int damage = 0;

        for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            String key = entry.getKey();
            JsonElement element = entry.getValue();

            if (key.equals("name")) {
                name = element.getAsString();
            } else if (key.equals("damage")) {
                damage = element.getAsInt();
            }
        }

        return name.isEmpty() ? ItemStack.EMPTY : new ItemStack(Item.REGISTRY.getObject(new ResourceLocation(name)), 1, damage);
    }
}
@@ -122,16 +122,132 @@
 mStack;%0A
+import net.minecraft.nbt.JsonToNBT;%0Aimport net.minecraft.nbt.NBTException;%0Aimport net.minecraft.nbt.NBTTagCompound;%0A
 import n
@@ -840,16 +840,150 @@
 age()));
+%0A        if (src.hasTagCompound()) %7B%0A            object.add(%22nbt%22, new JsonPrimitive(String.valueOf(src.getTagCompound())));%0A        %7D
 %0A%0A      
@@ -1294,16 +1294,41 @@
 age = 0;
+%0A        String nbt = %22%22;
 %0A%0A      
@@ -1693,16 +1693,105 @@
        %7D
+ else if (key.equals(%22nbt%22)) %7B%0A                nbt = element.getAsString();%0A            %7D
 %0A       
@@ -1784,33 +1784,32 @@
      %7D%0A        %7D
-%0A
 %0A        return 
@@ -1919,18 +1919,237 @@
 , damage
-);
+, getTag(nbt));%0A    %7D%0A%0A    private NBTTagCompound getTag(String string) %7B%0A        try %7B%0A            return JsonToNBT.getTagFromJson(string);%0A        %7D catch (NBTException nbtException) %7B%0A            return null;%0A        %7D
 %0A    %7D%0A%7D

Save NBT to json as well