Created
January 22, 2013 15:05
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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