Skip to content

Instantly share code, notes, and snippets.

@graingert
Forked from xuwei-k/EitherReadsExample.scala
Last active July 20, 2020 02:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save graingert/7b1c9d20fb5f4cb081dd5a640ca335f4 to your computer and use it in GitHub Desktop.
Save graingert/7b1c9d20fb5f4cb081dd5a640ca335f4 to your computer and use it in GitHub Desktop.
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