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

.serialization_json.1.4.3.source-code.JacksonTextFormat.kt Maven / Gradle / Ivy

There is a newer version: 1.5.4
Show newest version
package com.hexagonkt.serialization

import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.core.util.DefaultIndenter.SYSTEM_LINEFEED_INSTANCE
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.databind.ObjectWriter
import com.hexagonkt.serialization.JacksonHelper.createObjectMapper
import java.io.InputStream
import java.io.OutputStream
import kotlin.reflect.KClass

open class JacksonTextFormat(
    final override val extensions: LinkedHashSet,
    factoryGenerator: (() -> JsonFactory)? = null
) : SerializationFormat {

    val mapper =
        if (factoryGenerator == null) JacksonHelper.mapper
        else createObjectMapper(factoryGenerator())

    override val contentType = "application/${extensions.first()}"
    override val isBinary = false

    private val writer = createObjectWriter()

    private fun createObjectWriter(): ObjectWriter {
        val printer = DefaultPrettyPrinter().withArrayIndenter(SYSTEM_LINEFEED_INSTANCE)
        return mapper.writer(printer)
    }

    override fun serialize(obj: Any, output: OutputStream) = writer.writeValue(output, obj)
    override fun serialize(obj: Any): String = writer.writeValueAsString(obj)

    override fun  parse(input: InputStream, type: KClass): T =
        try {
            mapper.readValue(input, type.java)
        }
        catch (e: JsonProcessingException) {
            throw JacksonHelper.parseException(e)
        }

    override fun  parseObjects(input: InputStream, type: KClass): List =
        try {
            mapper.readValue(input, collectionType(List::class, type))
        }
        catch (e: JsonProcessingException) {
            throw JacksonHelper.parseException(e)
        }

    private fun > collectionType(coll: KClass, type: KClass<*>) =
        mapper.typeFactory.constructCollectionType(coll.java, type.java)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy