ru.inforion.lab403.common.extensions.json.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlin-extensions Show documentation
Show all versions of kotlin-extensions Show documentation
Kotlin extension methods and function for different Java libraries
package ru.inforion.lab403.common.extensions
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.readValue
import java.io.InputStream
fun ObjectMapper.enableTyping() {
// Java json serializer read long as int if:
// - it defined as value: Long but it shorter then long after serialization
enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE, JsonTypeInfo.As.EXISTING_PROPERTY)
}
fun jsonParser(
comments: Boolean = true,
indent: Boolean = true,
typing: Boolean = false
) = ObjectMapper().apply {
configure(JsonParser.Feature.ALLOW_COMMENTS, comments)
configure(SerializationFeature.INDENT_OUTPUT, indent)
registerModule(JodaModule())
registerModule(KotlinModule())
if (typing) enableTyping()
}
// https://stackoverflow.com/questions/3907929/should-i-declare-jacksons-objectmapper-as-a-static-field
// using several mappers and get at each time random mapper to prevent heavy deadlocks
val mappers = Array(16) { jsonParser() }
inline fun String.parseJson(m: ObjectMapper = mappers.random()) = m.readValue(this)
inline fun InputStream.parseJson(m: ObjectMapper = mappers.random()) = m.readValue(this)
inline fun Map.parseJson(m: ObjectMapper = mappers.random()): T = m.convertValue(this, T::class.java)
inline fun Any.parseJsonAsMap(m: ObjectMapper = mappers.random()): T = (this as Map).parseJson(m)
inline fun Any.parseJsonAsString(m: ObjectMapper = mappers.random()): T = (this as String).parseJson(m)
inline fun T.writeJson(m: ObjectMapper = mappers.random()) = m.writeValueAsString(this)