com.ancientlightstudios.quarkus.kotlin.openapi.JsonDeserializationExtensions.kt Maven / Gradle / Ivy
package com.ancientlightstudios.quarkus.kotlin.openapi
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.NullNode
import com.fasterxml.jackson.databind.node.ObjectNode
fun Maybe.asJson(objectMapper: ObjectMapper): Maybe = onNotNull {
try {
if (value.isEmpty()) {
success(null)
} else {
success(objectMapper.readValue(value, JsonNode::class.java))
}
} catch (_: Exception) {
failure(ValidationError("is not valid json", context))
}
}
@Suppress("unused")
fun Maybe.asObject(): Maybe = onNotNull {
when (this.value) {
is NullNode -> success(null)
is ObjectNode -> this@asObject as Maybe
else -> Maybe.Failure(context, ValidationError("is not a valid json object", context))
}
}
@Suppress("unused")
fun JsonNode?.findProperty(name: String, context: String): Maybe = Maybe.Success(context, this?.get(name))
@Suppress("unused")
fun Maybe.asList(): Maybe?> = onNotNull {
when (this.value) {
is NullNode -> success(null)
is ArrayNode -> success(this.value.toList())
else -> Maybe.Failure(context, ValidationError("is not a valid json object", context))
}
}
@Suppress("unused")
@JvmName("asStringFromJson")
fun Maybe.asString() = onNotNull {
when (value) {
is NullNode -> Maybe.Success(context, null)
is ObjectNode, is ArrayNode -> Maybe.Failure(context, ValidationError("is not a string", context))
else -> Maybe.Success(context, value.asText())
}
}
@Suppress("unused")
@JvmName("asIntFromJson")
fun Maybe.asInt() = asString().asInt()
@Suppress("unused")
@JvmName("asUIntFromJson")
fun Maybe.asUInt() = asString().asUInt()
@Suppress("unused")
@JvmName("asLongFromJson")
fun Maybe.asLong() = asString().asLong()
@Suppress("unused")
@JvmName("asULongFromJson")
fun Maybe.asULong() = asString().asULong()
@Suppress("unused")
@JvmName("asBigIntegerFromJson")
fun Maybe.asBigInteger() = asString().asBigInteger()
@Suppress("unused")
@JvmName("asFloatFromJson")
fun Maybe.asFloat() = asString().asFloat()
@Suppress("unused")
@JvmName("asDoubleFromJson")
fun Maybe.asDouble() = asString().asDouble()
@Suppress("unused")
@JvmName("asBigDecimalFromJson")
fun Maybe.asBigDecimal() = asString().asBigDecimal()
@Suppress("unused")
@JvmName("asBooleanFromJson")
fun Maybe.asBoolean() = asString().asBoolean()
@Suppress("unused")
@JvmName("asByteArrayFromJson")
fun Maybe.asByteArray() = asString().asByteArray()