KubeJS

KubeJS

61M Downloads

Re-add a toResultsJson method

justastranger opened this issue ยท 2 comments

commented

Describe the feature

The old ItemStackJS wrapper from 1.18.2 had a toResultJson method that was critical for creating custom JSON for custom recipes. With the removal of the wrapper, and Item.of returning a raw ItemStack, there is no longer a method available for this functionality. You can't just stick the ItemStack into the JSON object (creates recipes with null outputs) and you can't use toString since that doesn't produce JSON (Item.of("minecraft:bucket", 8).toString() -> 8 bucket). A utility function (Item.toResultJson(ItemStack) or Util.toResultJson(ItemStack)) that replicates this functionality for the newer versions of KubeJS would be a lifesaver

Additional info

No response

commented

I was able to come up with a way to use GSON and Mojang's CODECs to produce JSON for ItemStacks, but it would still be really nice if there was a method built into KubeJS.

const ItemStackClass = Java.loadClass("net.minecraft.class_1799");
const GsonBuilderClass = Java.loadClass("com.google.gson.GsonBuilder");
const JsonOps = Java.loadClass("com.mojang.serialization.JsonOps");
const GSON = new GsonBuilderClass().disableHtmlEscaping().create();

function toResultJson(itemstack){
	var encoded = ItemStackClass.CODEC.encode(itemstack, JsonOps.INSTANCE, JsonOps.INSTANCE.empty());
	if (encoded.result().isPresent()){
		return GSON.toJson(encoded.result().get());
	} else {
		throw "toResultJson: input could not be encoded, is it really an ItemStack?"
	}
}
commented

Learned that KubeJS injects a toJson method via mixin, making the above code snippet redundant. It does not, however, get called automatically meaning that you always need to serialize your ItemStacks yourself in order to use them in JSON.