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

codecs.basic.NonRecursiveJSONDecoderCodec.kt Maven / Gradle / Ivy

There is a newer version: 0.9.24
Show newest version
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() {}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy