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

com.increase.api.core.BaseDeserializer.kt Maven / Gradle / Ivy

The newest version!
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
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy