Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.3.7"
resolvers += "typesafe" at "http://typesafe.artifactoryonline.com/typesafe/releases"
scalaVersion := "2.11.4"
import JsEither._
case class Page(id: Int, name: String, screen_name: String, is_closed: Int, photo_50: String, photo_100: String, photo_200: String)
object Page {
implicit val format = Json.format[Page]
}
case class Profile(id: Int, first_name: String, last_name: String)
object Profile {
implicit val format = Json.format[Profile]
}
object EitherReadsExample {
def main(args: Array[String]): Unit = {
println(json.validate[Seq[Either[Profile, Page]]])
}
}
import play.api.libs.json._
// https://groups.google.com/d/topic/play-framework/anYvYB-8GYs/discussion
implicit object JsEither {
implicit def eitherReads[A, B](implicit A: Reads[A], B: Reads[B]): Reads[Either[A, B]] =
Reads[Either[A, B]] { json =>
A.reads(json) match {
case JsSuccess(value, path) => JsSuccess(Left(value), path)
case JsError(e1) => B.reads(json) match {
case JsSuccess(value, path) => JsSuccess(Right(value), path)
case JsError(e2) => JsError(JsError.merge(e1, e2))
}
}
}
implicit def eitherWrites[A, B](implicit A: Writes[A], B: Writes[B]): Writes[Either[A,B]] =
Writes[Either[A, B]] {
case Left(a) => A.writes(a)
case Right(b) => B.writes(b)
}
implicit def eitherFormat[A, B](implicit A: Format[A], B: Format[B]): Format[Either[A,B]] =
Format(eitherReads, eitherWrites)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment