All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jglrxavpok.hephaistos.json.NBTGsonWriter.kt Maven / Gradle / Ivy

The newest version!
package org.jglrxavpok.hephaistos.json

import com.google.gson.*
import org.jglrxavpok.hephaistos.nbt.*

class NBTGsonWriter internal constructor(val gson: Gson = GsonInstance) {

    companion object {
        val GsonInstance = Gson()

        @JvmStatic
        @JvmOverloads
        fun writer(gson: Gson = GsonInstance) = NBTGsonWriter(gson)

    }

    fun write(element: NBT): JsonElement {
        return when(element) {
            is NBTNumber -> JsonPrimitive(element.value)
            is NBTString -> JsonPrimitive(element.value)
            is NBTByteArray -> JsonArray().apply { element.forEach { add(it) } }
            is NBTLongArray -> JsonArray().apply { element.forEach { add(it) } }
            is NBTIntArray -> JsonArray().apply { element.forEach { add(it) } }
            is NBTList -> JsonArray().apply { element.forEach { add(write(it)) } }
            is NBTCompound -> JsonObject().apply {
                for((name, value) in element) {
                    add(name, write(value))
                }
            }

            is NBTEnd -> throw NBTException("Cannot convert TAG_End to a JsonElement")
            else -> error("Cannot serialize type ${element.ID}, not supported by this writer")
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy