Hi, I have the stupidest question on creating a si...
# android
f
Hi, I have the stupidest question on creating a simple data structure in Json format! Im somewhat confused when i tried creating it via mutableMapOf.. mutableListOf etc and the output is not like below. Anybody knows a simple kotlin magic to create this output:
[
{
"type" : "food",
"value" : "pizza, buger, pasta"
},
{
"type" : "drink",
"value" : "soda, Mountain Dew, redbull"
}
]
c
create a
Copy code
data class MyValues(val type: String, val value: String)
and then create a list like
Copy code
val mylist = listOf(
 MyValues("food", "pizza, burger, pasta"),
 MyValues("drink", "soda, Mountain Dew, redbull"
)
👍 1
f
Thats it?!! I've been twisting it left and right trying to use
mutableMapOf
and
Pair
etc!
c
Kotlin is not like JavaScript; Kotlin maps/lists are not the same as JSON objects/arrays. Creating the structure described by @Chrimaeon will give you the structure you are after, but not the actual String JSON respresentation. You'll need a proper serialization library to convert Kotlin classes into JSON strings, such as https://github.com/Kotlin/kotlinx.serialization
👍 2
f
Yeah I used Gson().toJson(mylist).toString() to convert it to the correct representation without "mylist" in it.
👍 1
I was just thinking this should be done via some kotlin syntax magic like those i mentioned above! didnt think of it being a simple "data class" with listOf
I was thinking like
val myData = mutableMapOf<String, String>().apply {
Pair(blah, blah)
}
but the output wasnt what i needed
c
Another option that doesn't need a custom class would be something like this:
Copy code
listOf(
    mapOf(
        "type" to "food",
        "value" to "pizza, burger, pasta",
    ),
    mapOf(
        "type" to "drink",
        "value" to "soda, Mountain Dew, redbull",
    ),
)
Generally-speaking, a JSON string can be manually converted to ad-hoc Kotlin code by replacing
[]
with
listOf()
,
{}
with
mapOf()
, and
:
with
to
. It's almost always better to use actual objects for type-safety, but this is an option
❤️ 1
🤯 1
g
It's possible to write a simple DSL which provides a shorter dynamic json creation DSL using invoke operators and infix functions, there are probably already some libraries for this, but it's not hard to write your own if it's a common use case for you
You probably can find existing implementations if google "Kotlin json DSL" or "Kotlin json builder"
👀 2
What is better really depends on your use case, I would prefer a safe solution, but there are different cases of course