Ask Your Question
0

How can I utilize Kotlinx.serialization to transform a JSON array into a Map<String, String>?

asked 2023-04-30 06:30:15 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-04-30 06:42:02 +0000

lakamha gravatar image

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
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-04-30 06:30:15 +0000

Seen: 13 times

Last updated: Apr 30 '23