I have a situation in my Play Framework application where a bunch of models depend on other models, which creates potential dangers when trying to serialize them to JSON. Also, there are a few properties in every model, which I do not want to expose to the client. Last, but not least, some of the properties in the moel instance which the web client receives are not really coming from the DB, but from a third-party web service.
I heard that it is possible to apply a custom serializer before rendering the object to JSON, but I would like to use an even simpler approach: DTO which is then serialized to JSON.
The question is, where I should I place the DTO conversion function for every Model class? Controller? Model? Maybe the best approach would be to follow the serializer strategy and create a few conversion classes - one for each Model?
My biggest fear is that the convertors should know about each other as well, because obviously I would like to turn each of the Book instances in an Author instance to DTO first, and then turn the Author in a DTO as well. Is this really bad?
In a standard Java EE app (Spring), you should use the Dozer framework to make conversion between model objects and DTOs.
In the Play! context, I should place the DTO and converters in a dedicated package, or in a subpackage of models
.
I'm using the model class as DTO and using the @NoJsonExpose
annotation for properties or other model dependencies that I do not want to expose.
Here is the implementation of @NoJsonExpose
annotation and the improved RenderJson
result object that considers it.
https://play.lighthouseapp.com/projects/57987/tickets/1605-propose-nojsonexpose-annotation-to-make-renderjsoners-life-better
Just need to override the Controller
's renderJson()
to use the new RenderJson
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With