実装抜粋
package controllers.presenters
import models.domains._
import play.api.libs.json._
import play.api.libs.functional.syntax._
trait JsonPostsPresenterImpl extends PostsPresenter {
implicit val postWrites = (
(__ \ "id").write[String].contramap((postId: PostId) => postId.toString) and
(__ \ "user_id").write[String].contramap((userId: UserId) => userId.toString) and
(__ \ "text").write[String].contramap((text: Text) => text.toString) and
(__ \ "posted_at").write[String].contramap((postedAt: PostedAt) => postedAt.toString)
)(unlift(Post.unapply))
override def present(input: Seq[Post]) = Json.toJson(input)
}
DDD的な実装をしているScalaアプリケーションだとクラスの構成要素がプリミティブ型ということはおそらく少なくて、ほぼほぼ専用の値クラスを用意している場合が多いんではないかと思う。
PlayのJsonコンビネータはドキュメントの例を見た感じ、プリミティブ型しか食えないっぽいので → コメントに追記があります。contramap
を使って値クラスからプリミティブ型への変換をしてやる処理が必要のようだ。