Kotlin Convert HashMap to Object/POJO (Kotlin Serialization)

Setup Kotlin Serialization

Edit Project build.gradle.

buildscript {
    ext {
        kotlin_version = '1.5.31'
    }

    dependencies {
        ...
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

Edit Module build.gradle.

plugins {
    id 'kotlin-android'
    id 'kotlinx-serialization''
}

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.1"
}

Edit proguard-rules.pro

Create Data class

@Serializableclass Place(    @SerialName("place_id") val placeId: String,     val name: String,    val types: List<Int>)

Map

val data = mapOf(    "place_id" to "abcd1234",    "name" to "A Good Place",    "types" to listOf(1, 9, 6))

Using JSONObject

val item = Json.decodeFromString<Place>(JSONObject(data).toString())

Using JsonElement

val item = Json.decodeFromJsonElement<Place>(data.toJsonObject())
/** * https://github.com/Kotlin/kotlinx.serialization/issues/746#issuecomment-737000705 */fun Any?.toJsonElement(): JsonElement {    return when (this) {        is Number -> JsonPrimitive(this)        is Boolean -> JsonPrimitive(this)        is String -> JsonPrimitive(this)        is Array<*> -> this.toJsonArray()        is List<*> -> this.toJsonArray()        is Map<*, *> -> this.toJsonObject()        is JsonElement -> this        else -> JsonNull    }}fun Array<*>.toJsonArray(): JsonArray {    val array = mutableListOf<JsonElement>()    this.forEach { array.add(it.toJsonElement()) }    return JsonArray(array)}fun List<*>.toJsonArray(): JsonArray {    val array = mutableListOf<JsonElement>()    this.forEach { array.add(it.toJsonElement()) }    return JsonArray(array)}fun Map<*, *>.toJsonObject(): JsonObject {    val map = mutableMapOf<String, JsonElement>()    this.forEach {        if (it.key is String) {            map[it.key as String] = it.value.toJsonElement()        }    }    return JsonObject(map)}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.