Skip to content

Instantly share code, notes, and snippets.

@alexanderjarvis
Created January 22, 2013 15:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alexanderjarvis/4595298 to your computer and use it in GitHub Desktop.
Save alexanderjarvis/4595298 to your computer and use it in GitHub Desktop.
Allow case classes with Tuple2 types to be represented as a Json Array with 2 elements e.g. (Double, Double)
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