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)}