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

ktx.json.serializers.kt Maven / Gradle / Ivy

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)
  }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy