I have a use case where I want to serialize a User entity to json. This user entity includes private fields I don't want to expose, such as password.
I'm using a custom OWrites to deal with this when I return a single user:
val userSafeWrites: OWrites[User] = (
(__ \ EMAIL_FIELD).write[String] ~
(__ \ FIRST_NAME_FIELD).write[String] ~
(__ \ LAST_NAME_FIELD).write[String] ~
(__ \ PHONE_NUMBER_FIELD).write[Option[String]] ~
(__ \ ID_FIELD).write[Long]
)(p => (p.email, p.firstName, p.lastName, p.phoneNumber, p._id.get))
and then I specify the OWrites instead of using the implicit:
Ok(Json.toJson(user)(User.userSafeWrites))
However, I have now to return a Set[User]
.
How can I do that? Do I need to implement a OWrites[Set[User]]
? I can understand how to do that if I was to return an object with a field name with the results, such as:
{
"users": [{user1}, {user2}]
}
However, I want to return simply an array, to comform to the output in other endpoints:
[{user1}, {user2}]
Or I should map each element of the set to a JsObject and apply the custom OWrites to each object? What would be the most efficient way to do that?
I feel this is something pretty simple and I'm just being a moron for not finding the answer myself.
OWrites[User]
in the implicit scope (either explicitly import it, or have it in the companion object ofUser
). Then, theWrites[Set[T]]
provided by Play will worker withT = User
, without more to do. – cchantep