如何从String转换为NBTCompoundTag?

时间:2015-01-03 12:49:29

标签: java minecraft minecraft-forge

我正在为Minecraft Forge模块编写一些代码,我需要在其中保存并从String恢复TileEntity定义。

要从TileEntity转换为String,我可以使用:

NBTCompoundTag nbt = new NBTCompoundTag();
TileEntity te = world.getTileEntity(x,y,z);
te.writeToNBT(nbt);
String nbtStr = nbt.toString();                         

但是,要从String转换回TileEntitiy,我缺少toString方法的反向(某种NBT解析器)。

String nbtStr;
NBTTagCompound nbtTag = new NBTTagCompound();
// this function does not exist
// nbtTag.parseString(nbtStr);
TileEntity te = TileEntity.createAndLoadEntity(nbtTag);
world.setTileEntity(x,y,z,te);

我搜索了各种文档,但无法找到可以将String表示转换为已解析的NBTCompoundTag对象的函数。

我的问题是,在持有NBT的字符串中解析的方法是什么?

1 个答案:

答案 0 :(得分:1)

从字符串转换回来的所需函数位于minecraft JsonToNBT类中。 Forge(还)没有对它进行反混淆处理,因此有一个相当无用的名称。

转换为字符串表示形式(实际上是JSON格式):

NBTTagCompound nbt = new NBTTagCompound();
String nbtJsonStr = nbt.toString();   

从字符串转换回NBTTagCompound:

String nbtJsonStr = "{foo:2,}";
NBTTagCompound nbt = (NBTTagCompound) JsonToNBT.func_150315_a(nbtJsonStr);

尽管如此,使用它最有可能使模块高度依赖于特定版本的Minecraft。