Bennnii
Bennnii

Reputation: 111

How to correctly deserialize ItemStack?

I'm working on a way to save ItemStacks in a MySQL-Database. The serializing and saving works fine but if I deserialize it, I just get the Item without the ItemMeta (e.g. Item isn't enchanted after deserializing).

Has anyone an idea how to deserialize it correctly? I found much about this on the internet but everything was outdatet and hasn't worked with 1.16.4.

My functions:

private static String itemStackToString(ItemStack item) {
    Gson gson = new Gson();
    return gson.toJson(item.serialize());
}

private static ItemStack stringToItemStack(String str) {
    Gson gson = new Gson();
    Map<String, Object> map = gson.fromJson(str, new TypeToken<Map<String, Object>(){}.getType());
    return ItemStack.deserialize(map);
}

Upvotes: 0

Views: 945

Answers (1)

Marcono1234
Marcono1234

Reputation: 6934

The issue is most likely that ItemStack.deserialize expects "meta" to be an instance of ItemMeta. However because you are telling Gson to deserialize the data as Map<String, Object>, it does not know about this requirement and deserializes the "meta" property value as Map instead.

You could possibly work around this by writing a custom Gson TypeAdapter which handles this, but it might be still rather brittle.

Maybe you can in some way use ConfigurationSection for serialization as shown here, but I don't know how well that works or if it is the proper (and safe) solution to this.

Upvotes: 1

Related Questions