1
2

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.

Play2のJsonで23要素以上のclassのReadsを作る

Last updated at Posted at 2015-01-14

現状のPlay2のJsonは公式ドキュメントに記載されている方法では、23要素以上あるclassのJsonのReads(デシリアライザ)を作成することができません。

その回避策としてxuweiさんが作成したplay-twenty-threeを使うことで23要素以上のJsonのReadsを作成することができますが、for式を使えば外部ライブラリに依存せずにReadsを作成することができます。
以下がfor式版のサンプルです。
追記: ※この方法だとエラー時の挙動が異なるためエラー箇所の特定が難しくなるようです

import play.api.libs.json.{ Json, Reads, __ }

case class Sample(
  v01: Int,
  v02: Int,
  v03: Int,
  v04: Int,
  v05: Int,
  v06: Int,
  v07: Int,
  v08: Int,
  v09: Int,
  v10: Int,
  v11: Int,
  v12: Int,
  v13: Int,
  v14: Int,
  v15: Int,
  v16: Int,
  v17: Int,
  v18: Int,
  v19: Int,
  v20: Int,
  v21: Int,
  v22: Int,
  v23: Int,
  v24: Int,
  v25: Int)

object Sample {

  implicit val reads: Reads[Sample] = {
    for (
      v01 <- (__ \ "v01").read[Int];
      v02 <- (__ \ "v02").read[Int];
      v03 <- (__ \ "v03").read[Int];
      v04 <- (__ \ "v04").read[Int];
      v05 <- (__ \ "v05").read[Int];
      v06 <- (__ \ "v06").read[Int];
      v07 <- (__ \ "v07").read[Int];
      v08 <- (__ \ "v08").read[Int];
      v09 <- (__ \ "v09").read[Int];
      v10 <- (__ \ "v10").read[Int];
      v11 <- (__ \ "v11").read[Int];
      v12 <- (__ \ "v12").read[Int];
      v13 <- (__ \ "v13").read[Int];
      v14 <- (__ \ "v14").read[Int];
      v15 <- (__ \ "v15").read[Int];
      v16 <- (__ \ "v16").read[Int];
      v17 <- (__ \ "v17").read[Int];
      v18 <- (__ \ "v18").read[Int];
      v19 <- (__ \ "v19").read[Int];
      v20 <- (__ \ "v20").read[Int];
      v21 <- (__ \ "v21").read[Int];
      v22 <- (__ \ "v22").read[Int];
      v23 <- (__ \ "v23").read[Int];
      v24 <- (__ \ "v24").read[Int];
      v25 <- (__ \ "v25").read[Int]
    ) yield Sample(
      v01,
      v02,
      v03,
      v04,
      v05,
      v06,
      v07,
      v08,
      v09,
      v10,
      v11,
      v12,
      v13,
      v14,
      v15,
      v16,
      v17,
      v18,
      v19,
      v20,
      v21,
      v22,
      v23,
      v24,
      v25
    )
  }
}

23要素以上のJsonなんてほとんどないのに、そのために外部ライブラリ入れるのもなんだかなー というときには使えるかもしれません。

1
2
4

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?