Spigot插件存储物品NBT时JSONObject转换异常求助
问题原因与解决方案
核心原因
你遇到的问题本质是:this.tags中的元素并非Java原生基本类型/包装类,而是Spigot的NBT标签对象(如NBTIntTag、NBTFloatTag、NBTIntArrayTag等)。当你直接将这些NBT对象传入org.json.JSONObject时,它会通过反射提取对象的公共字段(比如typeId、empty)进行序列化,而非读取标签存储的实际值。
而ret能正常转换,是因为它的map中存储的都是普通Java类型(String、Integer、Float等),org.json可以正确识别并序列化这些类型。
解决方案
需要遍历NBT标签时,将每个NBT对象转换为对应的Java原生类型,再存入Map中。示例代码如下:
Map<String, Object> map = new HashMap<>(); map.put("name", this.Name); map.put("amount", this.amount); map.put("data", this.data); map.put("damage", this.damage); map.put("rarity", this.rarity); map.put("id", this.materialId); JSONArray arr = new JSONArray(this.lore); Map<String, Object> nbt = new HashMap<>(); // 遍历NBT标签并转换为原生类型 for (String key : this.tags.keySet()) { NBTBase tag = this.tags.get(key); if (tag instanceof NBTIntTag) { nbt.put(key, ((NBTIntTag) tag).getAsInt()); } else if (tag instanceof NBTFloatTag) { nbt.put(key, ((NBTFloatTag) tag).getAsFloat()); } else if (tag instanceof NBTIntArrayTag) { nbt.put(key, ((NBTIntArrayTag) tag).getAsIntArray()); } else if (tag instanceof NBTStringTag) { nbt.put(key, ((NBTStringTag) tag).getAsString()); } else if (tag instanceof NBTLongTag) { nbt.put(key, ((NBTLongTag) tag).getAsLong()); } else if (tag instanceof NBTByteTag) { nbt.put(key, ((NBTByteTag) tag).getAsByte()); } // 根据你实际使用的NBT类型,补充对应的转换逻辑 } nbt.remove("display"); JSONObject n = new JSONObject(nbt); JSONObject ret = new JSONObject(map); ret.put("lore", arr); ret.put("tags", n); return ret;
验证说明
修改后,nbt Map中存储的都是Java原生类型,传入JSONObject后会被正确序列化为对应的值,比如isWand=1会被转为"isWand":1,而不是包含typeId和empty的对象结构。
内容的提问来源于stack exchange,提问作者nods 6325
相关产品推荐
相关产品推荐

