Manuel Pérez Alcolea
09/10/2023, 3:31 AMdata class TheData(
val postId: Long,
val content: String,
val authorId: Long,
)
These represent the content stored in the database. Now, when serialized to JSON, I want a few properties to be serialized "in a different way," and only in the context of sending it to a regular user. Instead of this:
{
"postId": 500,
"content": "hello",
"authorId": 322
}
I want them to get this, if (in the backend) I check the entry has been created by the requester:
{
"postId": 500,
"content": "hello",
"bySelf": true
}
The simplest solution I can think of would be to create a new serializable data class ThePublicData
and convert TheData
to them accordingly. Are there any elegant solutions for this? Should I avoid having a single class for multiple use cases in serialization? Hmm, I reading the official guide on polymorphism, I might find something useful.Christos Malliaridis
09/10/2023, 12:43 PMManuel Pérez Alcolea
09/10/2023, 6:56 PMcall.respond(myObject)
to send a response, but what if I want to serialize it in two different ways depending on who the response is for? Different data classes world work (myObject.toSomeOtherModel()
) but can it be done without new class definitions, and only with multiple serializers for the class? It sounds weird so I'm not asking for this solution, more like if it should be done like that and if it's feasibleChristos Malliaridis
09/10/2023, 10:14 PMif-else
condition and handle yourself the serialization of the response data.
But I personally prefer multiple data classes over custom serializers, it looks in my opinion cleaner and is easier to maintain. Doc comments would come in handy in this case, you could document data classes and fields as well as their usage. And once you don’t need a field anymore or need to add one, you don’t have to mess around with the serializers logic, but instead you can simply add or remove the field from the data class and update if necessary the mapper.
I think this is pretty much a preference and very case-specific you situation. Therefore, decide which solution looks best to you and go for it. You could also implement all options in question and decide by comparing the solutions in various scenarios.Manuel Pérez Alcolea
09/10/2023, 10:21 PM