NBT tag to ItemMeta

Discussion in 'Plugin Development' started by YalpYasis, Apr 30, 2024.

Thread Status:
Not open for further replies.
  1. Offline

    YalpYasis

    Hello, I have a database that contains all information about items that a player has.
    upload_2024-4-30_19-23-56.png
    meta_data is String metaData = item.getItemMeta().getAsString();

    How can I add ItemMeta for ItemStack to get an item with an NBT tag?

    // Get the Material from the itemId
    Material material = Material.matchMaterial(itemId);

    // Create the ItemStack
    ItemStack itemStack = new ItemStack(material, amount);

    // Add the ItemStack to the inventory
    player.getInventory().setItem(slot, itemStack);
     
  2. Offline

    KarimAKL

  3. Offline

    Machine Maker

    ItemMeta#getAsString specifically says it should NOT be relied upon as a serializable value. If you want the best way to store items, especially in a database where human-readability isn't required, using https://jd.papermc.io/paper/1.20/org/bukkit/inventory/ItemStack.html#serializeAsBytes() and storing it as a blob is better as the deserialization will run the itemstack through the data upgrader for new versions. It is also completely lossless whereas ConfigurationSerializable w/ItemStacks is a lossy conversion.
     
    KarimAKL likes this.
  4. Offline

    KarimAKL

    Could you elaborate on this for clarification? I read the source code for both methods and agree with you, but I'm curious about how it is a lossy conversion.
    What I could gather:
    * The Bukkit API uses a wrapper for a map containing the serialized ConfigurationSerializable instance, which in the case of an ItemStack is the version, type, amount, and metadata. The metadata is serialized by adding data such as display name, localized name, lore, model data, etc. as well as the internal NBT tags into a map.
    * The Paper method uses the internal NBT IO class to write the version into the item's compound tag and then write the compound tag's keys and values to a GZIP-compressed byte array output stream.
     
  5. Offline

    Machine Maker

    The serialization/deserialization between ItemMeta and the ConfigurationSection format does not keep the exact same information in the exact same format. Leading to an ItemStack serialized with it not stacking if you deserialize the same data. There are several examples of this, but I think the biggest, is that NBT supports multiple number types, whereas YAML does not. NBT has short, double, float, byte, int, and long. YAML does not support all of that. So if a byte NBT tag is serialized to YAML, the deserialized NBT will be different because it doesn't know it was a byte originally. Now, a lot of this is actually the fault of the whole ItemMeta system and not really of the serialization system, but regardless you end up in the same place.
     
    KarimAKL likes this.
Thread Status:
Not open for further replies.

Share This Page