4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scalaバッドノウハウメモ:PlayのJson.formatの罠

Posted at

ググっても英語記事が多くて面倒なので、解決したらメモを書いていくことにします。
あとQiitaのソースコードの書き方よくわかんないので適当に書く。

Json.format[A]に、フィールドが1つでそれがコレクションのcase classを渡すと怒られる。

toJson.scala
  case class Hoge(fuga:Option[Int], piyo:String)
  implicit val format = Json.format[Hoge]

とかだと問題なく動くのだけど、

toJson.scala
  case class Hoge(fuga:Option[Int])
  implicit val format = Json.format[Hoge]

とか書いちゃうと、Json.format[A]にcase classを指定する時に、No apply function found matching unapply parameters と怒られてしまう。

に書いてある通り、

toJson.scala
 case class A(value: List[Int])

  val areads = (__ \ 'value).read[List[Int]].map{ l => A(l) } // covariant map

  val awrites = (__ \ 'value).write[List[Int]].contramap{ a: A => a.value } // contravariant map

  val aformat = (__ \ 'value).format[List[Int]].inmap(  (l: List[Int]) => A(l), (a: A) => a.value ) // invariant = both    covariant and contravariant

とか書けば動くみたいなんだけど、記号が拒否反応を起こしてしまう人は、下の方に書いてあるやり方で、

toJson.scala
  object MyTypes {
   type DataPoints = Option[Int]
  }
  case class Hoge(fuga: MyTypes.DataPoints)
  implicit val format = Json.format[Hoge]

とか書くと怒られなくなる。

4
3
0

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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?