https://kotlinlang.org logo
#getting-started
Title
# getting-started
x

xun su

03/07/2023, 11:17 AM
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

Javier

03/07/2023, 11:25 AM
#serialization
a

Adam S

03/07/2023, 11:26 AM
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

Adam S

03/07/2023, 11:27 AM
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

xun su

03/07/2023, 11:35 AM
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))
}
19 Views