Skip to content

Instantly share code, notes, and snippets.

@Miuler
Forked from alexanderjarvis/Tuple2Format.scala
Created July 18, 2013 15:38
Show Gist options
  • Save Miuler/6030352 to your computer and use it in GitHub Desktop.
Save Miuler/6030352 to your computer and use it in GitHub Desktop.
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.data.validation._
implicit def tuple2Reads[A, B](implicit aReads: Reads[A], bReads: Reads[B]): Reads[Tuple2[A, B]] = Reads[Tuple2[A, B]] {
case JsArray(arr) if arr.size == 2 => for {
a <- aReads.reads(arr(0))
b <- bReads.reads(arr(1))
} yield (a, b)
case _ => JsError(Seq(JsPath() -> Seq(ValidationError("Expected array of two elements"))))
}
implicit def tuple2Writes[A, B](implicit aWrites: Writes[A], bWrites: Writes[B]): Writes[Tuple2[A, B]] = new Writes[Tuple2[A, B]] {
def writes(tuple: Tuple2[A, B]) = JsArray(Seq(aWrites.writes(tuple._1), bWrites.writes(tuple._2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment