Created
March 17, 2013 22:34
-
-
Save mandubian/5183939 to your computer and use it in GitHub Desktop.
Play2.1 JSON API: Reads a JsArray and then map on its elements applying Reads (cumulating errors)
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
// maybe we could add this one into Play... | |
// Reads a JsArray and then map on its elements applying Reads (cumulating errors) | |
def readJsArrayMap[A <: JsValue](transformEach: Reads[A]): Reads[JsArray] = Reads { js => js match { | |
case arr: JsArray => | |
arr.value.foldLeft(JsSuccess(Seq[JsValue]()): JsResult[Seq[JsValue]]) { (acc, e) => | |
acc.flatMap{ seq => | |
e.transform(transformEach).map( v => seq :+ v ) | |
} | |
}.map(JsArray(_)) | |
case _ => JsError("expected JsArray") | |
}} | |
// yours specific reader | |
val myReads = (__ \ "key1").json.pickBranch( | |
readJsArrayFoldLeft( | |
(__ \ "key2").json.pickBranch( | |
readJsArrayFoldLeft( | |
(__ \ "id").json.copyFrom(__.json.pick) | |
) | |
) | |
) | |
) |
I don't suppose this is any closer to making into Play, like your comments suggest? I found the helper method to be very useful for transforming a JsArray as output for my web services.
Thanks,
David P.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in myReads, shouldn't it be readJsArrayMap instead of readJsArrayFoldLeft ? :)