codecs.basic.NonRecursiveJSONDecoderCodec.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fluid-json-coding Show documentation
Show all versions of fluid-json-coding Show documentation
A JSON library written in pure Kotlin (coding extension)
package com.github.fluidsonic.fluid.json
internal abstract class NonRecursiveJSONDecoderCodec : AbstractJSONDecoderCodec() {
private val expectedFirstToken = when (decodableType.rawClass) {
Collection::class,
Iterable::class,
List::class,
Sequence::class,
Set::class ->
JSONToken.listStart
Map::class ->
JSONToken.mapStart
else -> error("Cannot decode $decodableType")
}
@Suppress("UNCHECKED_CAST")
override fun JSONDecoder.decode(valueType: JSONCodingType): Value {
if (nextToken != expectedFirstToken) {
throw JSONException.Schema(
message = "Cannot decode $nextToken as $valueType",
offset = offset,
path = path
)
}
val value = JSONParser.default.parseValueOrNull(this, withTermination = false)
return when {
Sequence::class.java.isAssignableFrom(valueType.rawClass.java) -> (value as Iterable<*>).asSequence() as Value
Set::class.java.isAssignableFrom(valueType.rawClass.java) -> (value as Iterable<*>).toSet() as Value
else -> value as Value
}
}
companion object {
inline fun create(): JSONDecoderCodec =
object : NonRecursiveJSONDecoderCodec() {}
}
}