[SOLVED] A way of serializing chests

Discussion in 'Spigot Plugin Development' started by kottalizer, Jul 7, 2015.

  1. kottalizer


    Is there a convenient class, library or method for serializing and/or de-serializing the contents of a chest? I would prefer if everything (except maybe the order) was kept intact; enchants, book contents, durability etc.
  2. Couldnt you just get a class that does this for a players inventory, but instead of getting the players inventory get the chests inventory?
  3. This should work, I am assuming you right click a chest:

    Code (Text):
        public void onPlayerInteract(PlayerInteractEvent e) {
            if (e.getAction() == Action.RIGHT_CLICK_BLOCK) {
                if ((e.getClickedBlock().getState() instanceof Chest)) {
                    Player player = e.getPlayer();
                    Chest localchest = (Chest) e.getClickedBlock().getState();
                    Map<String,Object> serializedInventory = localchest.getBlockInventory().getContents().serialize();

    Basically I am checking if my clicked block is a chest, if true, I am getting the Chests Inventory. From which I am getting an ItemStack Array which in the Spigot API is serializeable and also deserializeable.
  4. You can easily save an inventory by doing this:
    config.set("inventory", t.getInventory().getContents());

    Then to get it back:
    ItemStack[] content = ((List<ItemStack>) c.get("inventory")).toArray(new ItemStack[0]);
  5. kottalizer


    Thank you for your replies!

    I was almost going down the base64 route as I wasn't aware of the serialize() method (chest.getBlockInventory().getContents().serialize()).
    • Agree Agree x 1