|
| 1 | +/* |
| 2 | + * Copyright 2025 Lambda |
| 3 | + * |
| 4 | + * This program is free software: you can redistribute it and/or modify |
| 5 | + * it under the terms of the GNU General Public License as published by |
| 6 | + * the Free Software Foundation, either version 3 of the License, or |
| 7 | + * (at your option) any later version. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | + * GNU General Public License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU General Public License |
| 15 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 | + */ |
| 17 | + |
| 18 | +package com.lambda.config.serializer |
| 19 | + |
| 20 | +import com.google.gson.JsonDeserializationContext |
| 21 | +import com.google.gson.JsonDeserializer |
| 22 | +import com.google.gson.JsonElement |
| 23 | +import com.google.gson.JsonObject |
| 24 | +import com.google.gson.JsonSerializationContext |
| 25 | +import com.google.gson.JsonSerializer |
| 26 | +import net.minecraft.item.ItemStack |
| 27 | +import net.minecraft.nbt.StringNbtReader |
| 28 | +import net.minecraft.nbt.visitor.StringNbtWriter |
| 29 | +import net.minecraft.registry.Registries |
| 30 | +import net.minecraft.util.Identifier |
| 31 | +import java.lang.reflect.Type |
| 32 | + |
| 33 | +object ItemStackSerializer : JsonSerializer<ItemStack>, JsonDeserializer<ItemStack> { |
| 34 | + override fun serialize( |
| 35 | + stack: ItemStack, |
| 36 | + typeOfSrc: Type, |
| 37 | + context: JsonSerializationContext |
| 38 | + ): JsonElement = |
| 39 | + JsonObject().apply { |
| 40 | + addProperty("id", stack.item.registryEntry.key.get().value.toString()) |
| 41 | + addProperty("count", stack.count) |
| 42 | + stack.nbt?.let { addProperty("tag", StringNbtWriter().apply(it)) } |
| 43 | + } |
| 44 | + |
| 45 | + override fun deserialize( |
| 46 | + json: JsonElement, |
| 47 | + typeOfT: Type, |
| 48 | + context: JsonDeserializationContext |
| 49 | + ): ItemStack { |
| 50 | + val id = json.asJsonObject.get("id").asString |
| 51 | + val count = json.asJsonObject.get("count").asInt |
| 52 | + val nbt = json.asJsonObject?.get("tag")?.asString |
| 53 | + |
| 54 | + val item = Registries.ITEM.get(Identifier(id)) |
| 55 | + |
| 56 | + return ItemStack(item, count).apply { nbt?.let { setNbt(StringNbtReader.parse(it)) } } |
| 57 | + } |
| 58 | +} |
0 commit comments