Hi, could someone tell me how to define the `data...
# getting-started
x
Hi, could someone tell me how to define the
data class
to get json like this :
Copy code
{
  "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:
Copy code
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?
j
#serialization
a
If you have some data with dynamic keys, that’s represented with a <https://kotlinlang.org/docs/collections-overview.html#map%7CMap&lt;K, V>>
a
the keys in your examples are
"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>
x
take the example from the link above:
Copy code
@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))
}