I have this ProgramDto : ```data class ProgramDto(...
# spring
d
I have this ProgramDto :
Copy code
data class ProgramDto(
    val id: Long?,
    val title: String,
    val description: String,
    var images: List<ImageDto>? = emptyList()
)
that may (or not) have Sessions. Sometime the Front end needs it, sometimes it doesn’t. So I’ve created another Dto called ProgramWithSessionsDto. And then I added this function in ProgramDto that converts the ProgramDto to a ProgramWithSessionsDto:
Copy code
fun ProgramDto.toProgramWithSessionsDto(): ProgramWithSessionsDto = ProgramWithSessionsDto(
    id = id,...
ProgramWithSessionsDto, is this:
Copy code
data class ProgramWithSessionsDto(
    val id: Long?,
    val title: String,
    val description: String,
    var images: List<ImageDto>? = emptyList(),
    var sessions: List<SessionDto>? = emptyList()
)
But that’s a lot of Dtos I’m going to add to my project. Is there anyway I could simply add this to my ProgramDto:
Copy code
var sessions: List<SessionDto>? = emptyList(),
but not return it (the sessions) if I don’t need to ? and then I could get rid of ProgramWithSessionsDto.
r
Have you thought of composition over inheritance? Assuming you're using Jackson, you could make use of
@JsonUnwrapped
.
d
I’m not aware that I’m using Jackson. I believe I need to add it as a dependency. using
@JsonUnwrapped
does it mean the sessions key won’t even be included in the json ?
r
In this model, you'd keep the two DTO classes, but
ProgramWithSessionsDto
would contain a
ProgramDto
rather than the individual attributes. If you then add
@JsonUnwrapped
, the JSON structure would look the same as now.
d
ok thanks @Raimund Klein I’ll give it a try 🙂
r
alternatively, you could annotate the class with
@JsonInclude(JsonInclude.Include.NON_EMPTY)
, which means that only non-null and non-empty fields will end up in the json. So if the
sessions
field contains an empty list, it won't be serialized
👍 1
d
Thanks @Riccardo Lippolis exaclty what I was looking for 🙂