티스토리 뷰

공부

[kotlin] toObject, toJson

승가비 2022. 11. 2. 11:59
728x90
    @Test
    fun toObject() {
        // given
        val expected = mapOf(
            "a" to 1,
            "b" to 2,
        )
        val json = "{\"a\":1,\"b\":2}"

        // when
        val map: Map<String, Int> = json.toObject()

        // then
        assertEquals(expected, map)
    }

    @Test
    fun toJson() {
        // given
        val expected = "{\"a\":1,\"b\":2}"
        val obj = mapOf(
            "a" to 1,
            "b" to 2,
        )

        // when
        val json = obj.toJson(false)

        // then
        assertEquals(expected, json)
    }
 
inline fun <reified T> String.toObject(): T {
    return JacksonUtil.toObject(this)
}

fun Any?.toJson(isBeauty: Boolean? = true): String {
    if (this is String) {
        return this
    }

    return JacksonUtil.toJson(this, isBeauty)
}
 
object JacksonUtil {
    val objectMapper: ObjectMapper = ObjectMapper()
        .registerModule(KotlinModule.Builder().build())
        .registerModule(JavaTimeModule())
        .registerModule(AfterburnerModule())
        .configure(SerializationFeature.INDENT_OUTPUT, true)
        .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
        .registerModule(
            JavaTimeModule().apply {
                addDeserializer(LocalDate::class.java, LocalDateDeserializer(DateTimeFormatter.ISO_DATE))
                addDeserializer(
                    LocalDateTime::class.java,
                    LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME)
                )
            }
        )

    fun toJson(obj: Any?, isBeauty: Boolean? = true): String {
        if (obj == null) {
            return ""
        }

        val json = objectMapper.writeValueAsString(obj)

        return if (isBeauty!!) {
            json
        } else {
            json.removeSpace()
        }
    }
    
    inline fun <reified T> toObject(s: String): T {
        return objectMapper.readValue(s, object : TypeReference<T>() {})
    }
}
728x90
댓글