LoginSignup
2
1

More than 5 years have passed since last update.

PlayのJsonコンビネータでWritesにcontramapを使う

Last updated at Posted at 2018-06-17
実装抜粋
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 を使って値クラスからプリミティブ型への変換をしてやる処理が必要のようだ。 → コメントに追記があります。

2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1