[Solved] Casting String To ItemStack

Hello, so I have a String: “[email protected]” aka a String version of an ItemStack. When I try to cast the string into an ItemStack, I receive an error from Eclipse: “Can not cast from String to ItemCast”. Any help? Thanks!

You can’t. It’s that simple. Where do you get the string representation from. Why a string?

The String was derived from a List<String>, which contains a list of ItemStacks that were saved onto a configuration file.

Then in the configuration file as for an ItemStack or an ItemType, not a String

You can’t cast directly from a primitive String to an ItemStack, the good news is that ItemStack is DataSerializable meaning you can easily serialize and deserialize it from a config node so for example to save an itemstack to a config node you would do:

myConfigNode.setValue(TypeToken.of(ItemStack.class), myItemStack);

Similarly to read an ItemStack from a config node you can do:

ItemStack myItemStack = myConfigNode.getValue(TypeToken.of(ItemStack.class));

1 Like

So this is the method I use to add items to my config file:

	public static void addItemToClass(String arenaName, String className, ItemStack itemStack){

    ConfigurationNode itemsNodeTarget = UnversalConfigs.getConfig(classConfig).getNode((Object[]) ("Arena." + arenaName + ".ArenaClasses." + className + ".items").split("\\."));
	String items = itemsNodeTarget.getString();
	String newItem = (itemStack + ",");
	UnversalConfigs.setValue(classConfig, itemsNodeTarget.getPath(), (items + newItem));

I have tried to retrieve individual ItemStacks, by interpreting your approach, but I can not seem to figure out how to implement your example using my data manipulator. Any more suggestions? Thanks :smile:

I would recommend taking a look at the configuration node documentation to get a feel for saving and loading objects to config nodes. I’m not familiar with the UniversalConfigs utility class so I’m not entirely sure how it works. However, there’s no need to manually insert “,” and build the list by hand. In addition to saving individual data serializable objects to config nodes you can also save any List or Map of serializable types.

So for example, to save a List<ItemStack> to a config node the syntax would be:

myConfigNode.setValue(new TypeToken<List<ItemStack>() {}, myItemStackList);

To read the list back you could do:

List<ItemStack> myItemStackList = myConfigNode.getValue(new TypeToken<List<ItemStack>() {});

1 Like