Skip to content

Instantly share code, notes, and snippets.

@NikkyAI
Last active September 11, 2018 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NikkyAI/2e2891ccf67d423c523311f0b43ca57b to your computer and use it in GitHub Desktop.
Save NikkyAI/2e2891ccf67d423c523311f0b43ca57b to your computer and use it in GitHub Desktop.
package voodoo.util.json
import io.ktor.client.call.TypeInfo
import io.ktor.client.features.json.JsonSerializer
import io.ktor.client.response.HttpResponse
import io.ktor.client.response.readText
import io.ktor.http.ContentType
import io.ktor.http.content.OutgoingContent
import io.ktor.http.content.TextContent
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialContext
import kotlinx.serialization.UpdateMode
import kotlinx.serialization.json.JSON
import kotlinx.serialization.serializer
import kotlin.reflect.KClass
class KotlinxSerializer (
unquoted: Boolean = false,
indented: Boolean = false,
indent: String = " ",
nonstrict: Boolean = false,
updateMode: UpdateMode = UpdateMode.OVERWRITE,
context: SerialContext? = null,
block: SerialContext.() -> Unit = {}
) : JsonSerializer {
private val json = JSON(
unquoted = unquoted,
indented = indented,
indent = indent,
nonstrict = nonstrict,
updateMode = updateMode,
context = context
)
init {
json.context?.apply {
block()
}
}
override fun write(data: Any): OutgoingContent {
val clazz: KClass<*> = data::class
val serializer = clazz.serializer()
@Suppress("UNCHECKED_CAST")
return TextContent(json.stringify(serializer as KSerializer<Any>, data), ContentType.Application.Json)
}
override suspend fun read(type: TypeInfo, response: HttpResponse): Any {
return json.parse(type.type.serializer(), response.readText())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment