com.increase.api.core.BaseDeserializer.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of increase-java-core Show documentation
Show all versions of increase-java-core Show documentation
An SDK library for increase
package com.increase.api.core
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.ObjectCodec
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.BeanProperty
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JavaType
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.deser.ContextualDeserializer
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import kotlin.reflect.KClass
abstract class BaseDeserializer(type: KClass) :
StdDeserializer(type.java), ContextualDeserializer {
override fun createContextual(
context: DeserializationContext,
property: BeanProperty?
): JsonDeserializer {
return this
}
override fun deserialize(parser: JsonParser, context: DeserializationContext): T {
return parser.codec.deserialize(parser.readValueAsTree())
}
protected abstract fun ObjectCodec.deserialize(node: JsonNode): T
protected fun ObjectCodec.tryDeserialize(
node: JsonNode,
type: TypeReference,
validate: (T) -> Unit = {}
): T? {
return try {
readValue(treeAsTokens(node), type).apply(validate)
} catch (e: JsonMappingException) {
null
} catch (e: RuntimeException) {
null
}
}
protected fun ObjectCodec.tryDeserialize(
node: JsonNode,
type: JavaType,
validate: (T) -> Unit = {}
): T? {
return try {
readValue(treeAsTokens(node), type).apply(validate)
} catch (e: JsonMappingException) {
null
} catch (e: RuntimeException) {
null
}
}
}