<pastes.dev/evcIOGa1jM> The link above shows the c...
# serialization
m
pastes.dev/evcIOGa1jM The link above shows the code related to the question I want to ask—it’s a serialization issue. The JSON format is as follows:
Copy code
{
  "todos": [],
  "total": 254,
  "skip": 0,
  "limit": 30
}
So, do I absolutely have to use two DTOs (@Serializable)? Do I really have to use two—`TaskDto` and
TasksResponse
, which contains it? If so, later on,
Copy code
{
"code": 200,
"message": null,
"content": {
// data
}
}
Here, “data” refers to everything—it’s just formatted like that. To achieve that,
Copy code
@Serializable
data class Dto<T>(
val code: Int,
val message: String? = null,
val content: T
)
Do I absolutely have to create one in this format to extract it? I’ve always been concerned that doing it that way would require too many classes.
a
If you want type safety you kind of have to define the types. I’m not aware of any good way to define “nested” types in-line, as you do with JSON, you have to extract each leaf type and specify them as separate classes (like TasksResponse and TaskDto). In theory you could do inline classes for organization, but in practice that becomes un-ergonomic pretty quickly:
Copy code
// from memory, not tested in IDE but roughly:
data class TasksResponse(
  val todos: List<TaskDto>, 
  val total: Int, 
  val skip: Int, 
  val limit: Int) {
    data class TaskDto(
      val id: Int, 
      val todo: String, 
      val completed: Boolean, 
      val userId: Int
    )
}
another lever you can use is to not define types but instead refer to the JsonObject family and reference fields directly. kotlinlang.org/api/kotlinx.serialization/…/-json-object I think this feels brittle and i tend to avoid it, but if you only care about some deeply nested part of the json i guess there is a case for it
m
ohh just add TaskDto in TasksResponse??