1 | initial version |
Here's an example of how to do it:
Assuming you have the following JSON array:
[
{"key": "foo", "value": "bar"},
{"key": "baz", "value": "qux"}
]
You can define a data class to represent each item in the array:
@Serializable
data class KeyValue(val key: String, val value: String)
Then, you can use the Json.decodeFromString()
function to deserialize the JSON array into a list of KeyValue
objects, and then use the associate()
function to transform it into a Map<String, String>
:
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
val jsonString = """[
{"key": "foo", "value": "bar"},
{"key": "baz", "value": "qux"}
]"""
val keyValueList = Json.decodeFromString<List<KeyValue>>(jsonString)
val keyValueMap = keyValueList.associate { it.key to it.value }
The resulting keyValueMap
will be a Map<String, String>
with the keys and values from the JSON array:
val expectedMap = mapOf("foo" to "bar", "baz" to "qux")
println(keyValueMap == expectedMap) // true