37 lines
1.1 KiB
Kotlin
37 lines
1.1 KiB
Kotlin
package ru.dbotthepony.kstarbound.defs
|
|
|
|
import com.google.gson.JsonSyntaxException
|
|
import com.google.gson.TypeAdapter
|
|
import com.google.gson.stream.JsonReader
|
|
import com.google.gson.stream.JsonToken
|
|
import com.google.gson.stream.JsonWriter
|
|
|
|
data class MaterialReference(
|
|
val id: Int?,
|
|
val name: String?
|
|
) {
|
|
init {
|
|
require(id != null || name != null) { "At least ID or material string ID should be not null" }
|
|
}
|
|
|
|
companion object : TypeAdapter<MaterialReference>() {
|
|
override fun write(out: JsonWriter, value: MaterialReference) {
|
|
if (value.id != null) {
|
|
out.value(value.id)
|
|
} else {
|
|
out.value(value.name!!)
|
|
}
|
|
}
|
|
|
|
override fun read(`in`: JsonReader): MaterialReference {
|
|
if (`in`.peek() == JsonToken.NUMBER) {
|
|
return MaterialReference(id = `in`.nextInt(), name = null)
|
|
} else if (`in`.peek() == JsonToken.STRING) {
|
|
return MaterialReference(id = null, name = `in`.nextString())
|
|
} else {
|
|
throw JsonSyntaxException("Invalid material reference: ${`in`.peek()} (must be either an Integer or String), near ${`in`.path}")
|
|
}
|
|
}
|
|
}
|
|
}
|