Advertisement
Guest User

Item Serializer

a guest
Mar 27th, 2013
47
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class ItemSerialization {
  2.    public static String toBase64(Inventory inventory) {
  3.        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  4.        DataOutputStream dataOutput = new DataOutputStream(outputStream);
  5.        NBTTagList itemList = new NBTTagList();
  6.        
  7.        // Save every element in the list
  8.        for (int i = 0; i < inventory.getSize(); i++) {
  9.            NBTTagCompound outputObject = new NBTTagCompound();
  10.            CraftItemStack craft = getCraftVersion(inventory.getItem(i));
  11.            
  12.            // Convert the item stack to a NBT compound
  13.            if (craft != null)
  14.                CraftItemStack.asNMSCopy(craft).save(outputObject);
  15.            itemList.add(outputObject);
  16.        }
  17.  
  18.        // Now save the list
  19.        NBTBase.a(itemList, dataOutput);
  20.  
  21.        // Serialize that array
  22.        return Base64Coder.encodeLines(outputStream.toByteArray());
  23.    }
  24.    
  25.    public static Inventory fromBase64(String data) {
  26.        ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
  27.        NBTTagList itemList = (NBTTagList) NBTBase.b(new DataInputStream(inputStream));
  28.        Inventory inventory = new CraftInventoryCustom(null, itemList.size());
  29.  
  30.        for (int i = 0; i < itemList.size(); i++) {
  31.            NBTTagCompound inputObject = (NBTTagCompound) itemList.get(i);
  32.            
  33.            if (!inputObject.isEmpty()) {
  34.                inventory.setItem(i, CraftItemStack.asCraftMirror(
  35.                    net.minecraft.server.v1_5_R2.ItemStack.createStack(inputObject)));
  36.            }
  37.        }
  38.        
  39.        // Serialize that array
  40.        return inventory;
  41.    }
  42.    
  43.    private static CraftItemStack getCraftVersion(ItemStack stack) {
  44.        if (stack instanceof CraftItemStack)
  45.            return (CraftItemStack) stack;
  46.        else if (stack != null)
  47.            return CraftItemStack.asCraftCopy(stack);
  48.        else
  49.            return null;
  50.    }
  51. }
Advertisement
RAW Paste Data Copied
Advertisement