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

me.kuku.utils.JacksonUtils.kt Maven / Gradle / Ivy

@file:Suppress("UNCHECKED_CAST")

package me.kuku.utils

import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode

object JacksonUtils {
    @JvmStatic
    val objectMapper: ObjectMapper = ObjectMapper()
        .setSerializationInclusion(JsonInclude.Include.NON_NULL)
        .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
        .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
        .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
        .findAndRegisterModules()

    @JvmStatic
    fun toJsonString(any: Any): String {
        return objectMapper.writeValueAsString(any)
    }

    @JvmStatic
    fun parse(json: String): JsonNode {
        return objectMapper.readTree(json)
    }

    @JvmStatic
    fun  parseObject(json: String, clazz: Class): T {
        return objectMapper.readValue(json, clazz)
    }

    inline fun  parseObject(json: String): T {
        return objectMapper.readValue(json, object: TypeReference(){})
    }

    @JvmStatic
    fun  parseArray(json: String, clazz: Class): MutableList {
        return objectMapper.readerFor(clazz).readValues(json).readAll()
    }

    inline fun  parseArray(json: String): List {
        return objectMapper.readValue(json, object: TypeReference>(){})
    }

    @JvmStatic
    fun createObjectNode(): ObjectNode {
        return objectMapper.createObjectNode()
    }

    @JvmStatic
    fun createArrayNode(): ArrayNode {
        return objectMapper.createArrayNode()
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy