Advertisement
Guest User

Untitled

a guest
Sep 4th, 2013
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.65 KB | None | 0 0
  1. package lib
  2.  
  3. import play.api.libs.json._
  4. import Json._
  5. import scala.annotation.implicitNotFound
  6. import play.api.data.validation.ValidationError
  7. import scala.collection.mutable.LinkedHashMap
  8.  
  9. trait CustomReads {
  10.     /**
  11.    * Deserializer for LinkedHashMap[String,V] types.
  12.    */
  13.   implicit def linkedHashMapReads[V](implicit fmtv: Reads[V]): Reads[scala.collection.mutable.LinkedHashMap[String, V]] = new Reads[scala.collection.mutable.LinkedHashMap[String, V]] {
  14.     def reads(json: JsValue) = json match {
  15.       case JsObject(m) => {
  16.         // first validates prod separates JsError / JsResult in an Seq[Either( (key, errors, globals), (key, v, jselt) )]
  17.         // the aim is to find all errors prod then to merge them all
  18.         var hasErrors = false
  19.  
  20.         val r = m.map {
  21.           case (key, value) =>
  22.             fromJson[V](value)(fmtv) match {
  23.               case JsSuccess(v, _) => Right((key, v, value))
  24.               case JsError(e) =>
  25.                 hasErrors = true
  26.                 Left(e.map { case (p, valerr) => (JsPath \ key) ++ p -> valerr })
  27.             }
  28.         }
  29.  
  30.         // if errors, tries to merge them into a single JsError
  31.         if (hasErrors) {
  32.           val fulle = r.filter(_.isLeft).map(_.left.get)
  33.             .foldLeft(List[(JsPath, Seq[ValidationError])]())((acc, v) => acc ++ v)
  34.           JsError(fulle)
  35.         } // no error, rebuilds the map
  36.         else JsSuccess(r.filter(_.isRight).map(_.right.get).map { v => v._1 -> v._2 }.toMap.asInstanceOf[scala.collection.mutable.LinkedHashMap[String,V]])
  37.       }
  38.       case _ => JsError(Seq(JsPath() -> Seq(ValidationError("error.expected.jsobject"))))
  39.     }
  40.   }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement