-
-
Save graingert/7b1c9d20fb5f4cb081dd5a640ca335f4 to your computer and use it in GitHub Desktop.
This file contains 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
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.3.7" | |
resolvers += "typesafe" at "http://typesafe.artifactoryonline.com/typesafe/releases" | |
scalaVersion := "2.11.4" |
This file contains 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 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]]]) | |
} | |
} |
This file contains 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._ | |
// 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