ktx.json.serializers.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ktx-json Show documentation
Show all versions of ktx-json Show documentation
libGDX JSON serialization utilities for Kotlin applications.
The newest version!
package ktx.json
import com.badlogic.gdx.utils.Json
import com.badlogic.gdx.utils.JsonValue
/**
* Wrapping interface around [com.badlogic.gdx.utils.Json.Serializer].
* Improves typing by adding nullability information and changes default parameter names.
*/
interface JsonSerializer : Json.Serializer {
override fun read(json: Json, jsonValue: JsonValue, type: Class<*>?): T
override fun write(json: Json, value: T, type: Class<*>?)
}
/**
* Wrapping interface around [com.badlogic.gdx.utils.Json.Serializer]. Provides null-safety
* and convenient interface for serializer that is only able to [read].
* Unlike libGDX [com.badlogic.gdx.utils.Json.ReadOnlySerializer], the default implementation of
* the [write] method throws [UnsupportedOperationException].
*/
interface ReadOnlyJsonSerializer : JsonSerializer {
override fun write(json: Json, value: T, type: Class<*>?) =
throw UnsupportedOperationException("Read-only serializers do not support write method.")
}
/**
* Factory function to create a [ReadOnlyJsonSerializer] from lambda.
*/
inline fun readOnlySerializer(crossinline reader: (Json, JsonValue, Class<*>?) -> T): Json.Serializer =
object : ReadOnlyJsonSerializer {
override fun read(json: Json, jsonValue: JsonValue, type: Class<*>?): T = reader(json, jsonValue, type)
}
/**
* Factory function to create a simplified [ReadOnlyJsonSerializer], which accepts only [JsonValue].
*/
inline fun readOnlySerializer(crossinline read: (JsonValue) -> T): Json.Serializer =
object : ReadOnlyJsonSerializer {
override fun read(json: Json, jsonValue: JsonValue, type: Class<*>?): T = read(jsonValue)
}