com.bybutter.sisyphus.jackson.Json.kt Maven / Gradle / Ivy
package com.bybutter.sisyphus.jackson
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import java.io.InputStream
import java.io.Reader
object Json : JacksonFormatSupport() {
override val mapper: ObjectMapper by lazy {
ObjectMapper().findAndRegisterModules()
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(JsonParser.Feature.IGNORE_UNDEFINED, true)
.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true)
}
}
inline fun String?.parseJsonOrNull(): T? {
this ?: return null
return try {
Json.deserialize(this, object : TypeReference() {})
} catch (e: Exception) {
null
}
}
inline fun String?.parseJsonOrDefault(value: T): T {
return this.parseJsonOrNull() ?: value
}
inline fun String.parseJson(): T =
Json.deserialize(this, object : TypeReference() {})
inline fun Reader?.parseJsonOrNull(): T? {
this ?: return null
return try {
Json.deserialize(this, object : TypeReference() {})
} catch (e: Exception) {
null
}
}
inline fun Reader?.parseJsonOrDefault(value: T): T {
return this.parseJsonOrNull() ?: value
}
inline fun Reader.parseJson(): T =
Json.deserialize(this, object : TypeReference() {})
inline fun InputStream?.parseJsonOrNull(): T? {
this ?: return null
return try {
Json.deserialize(this, object : TypeReference() {})
} catch (e: Exception) {
null
}
}
inline fun InputStream?.parseJsonOrDefault(value: T): T {
return this.parseJsonOrNull() ?: value
}
inline fun InputStream.parseJson(): T =
Json.deserialize(this, object : TypeReference() {})
fun Any.toJson(): String = Json.serialize(this)
© 2015 - 2024 Weber Informatics LLC | Privacy Policy