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
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-04-30 06:30:15 +0000
Seen: 13 times
Last updated: Apr 30 '23
Why can't IntelliJ IDEA detect the Kotlin multiplatform library?
How to implement map function on Kotlin's Stateflow?
What is the correlation between coroutines and the Kotlin Gradle Plugin?
When the library throws a JsonDataException, why does the Kotlin Moshi adapter return null?
What are the typical approaches found in a Gradle build script?
Which languages are appropriate to use for a contemporary website?