xun su
03/07/2023, 11:17 AMdata class
to get json like this :
{
"2022": [
{
"name": "foo",
"age": 12
},
{
"name": "bar",
"age": 12
}
],
"2023": [
{
"name": "baz",
"age": 12
}
]
}
I know little about serialization and this is what I wanna do:
import kotlinx.serialization.Serializable
@Serializable
data class Person(
var name: String,
var age: int,
) {}
@Serializable
data class Response(
var ???:Collection<Person> // key is year, what should I put here ?
){
}
or should I take another way?Javier
03/07/2023, 11:25 AMAdam S
03/07/2023, 11:26 AMJavier
03/07/2023, 11:26 AMAdam S
03/07/2023, 11:27 AM"2022"
and "2023"
, which are Strings. So that’s the key-type. The values are a list of People
, so the map’s value type is List<Person>
xun su
03/07/2023, 11:35 AM@Serializable
class Project(val name: String)
fun main() {
// I was thinking I have to define a data class with @Serializable for the map
// maybe I was wrong
val map = mapOf(
1 to Project("kotlinx.serialization"),
2 to Project("kotlinx.coroutines")
)
println(Json.encodeToString(map))
}