We can achieve without using play-json-extensions. Suppose we have a case class of more than 22 fields like below:
case class Foo(
A: Int,
B: Option[Int],
C: String,
D: Option[String],
E: Seq[String],
F: Date
more fields..
)
Now we will split and group the fields into some groups and write formats.
val fooFormat1: OFormat[(Int, Option[Int], String)] =
((__ \ "A").format[Long]
~ (__ \ "B").format[Option[Long]]
~ (__ \ "C").format[Option[Long]]).tupled
val fooFormat2: OFormat[(Option[String], Seq[String], Date)] =
((__ \ "D").format[Long]
~ (__ \ "E").format[Option[Long]]
~ (__ \ "F").format[Option[Long]]).tupled
And finally merge all the formats into one format.
implicit val fooFormat: Format[Foo] = (fooFormat1 ~ fooFormat2)({
case ((a, b, c), (d, e, f)) =>
new Foo(a, b, c, d, e, f)
}, (foo: Foo) => ((
foo.A,
foo.B,
foo.C
), (
foo.D,
foo.E,
foo.F
)))
We need to import function syntax like below:
import play.api.libs.functional.syntax._
Now, play can not serialize/deserialize optional and date fields. So, we need to write implicit formats for optional and date fields like below:
implicit object DateFormat extends Format[java.util.Date] {
val format = new java.text.SimpleDateFormat("yyyy-MM-dd")
def reads(json: JsValue): JsResult[java.util.Date] = JsSuccess(format.parse(json.as[String]))
def writes(date: java.util.Date): JsString = JsString(format.format(date))
}
implicit def optionFormat[T: Format]: Format[Option[T]] = new Format[Option[T]] {
override def reads(json: JsValue): JsResult[Option[T]] = json.validateOpt[T]
override def writes(o: Option[T]): JsValue = o match {
case Some(t) => implicitly[Writes[T]].writes(t)
case None => JsNull
}
}
That's all we need to write Writes for case classes more than 22 fields.
You can read my article here..