Skip to content

Instantly share code, notes, and snippets.

@mikesname
Created September 12, 2016 22:52
Show Gist options
  • Save mikesname/53563ea6b011a8ce9b85da23a0771b4e to your computer and use it in GitHub Desktop.
Save mikesname/53563ea6b011a8ce9b85da23a0771b4e to your computer and use it in GitHub Desktop.
implicit def longMapReads[T](implicit r: Reads[T]): Reads[Map[Long, T]] = Reads[Map[Long, T]] { jv =>
jv.validate[Map[String, T]].flatMap { obj =>
obj.foldLeft[JsResult[Map[Long,T]]](JsSuccess(Map.empty)) {
case (JsSuccess(o, p), (k, v)) =>
try {
JsSuccess(o + (k.toLong -> v))
} catch {
case e: IllegalArgumentException =>
val e = ValidationError(s"Value: '$k' cannot be converted to a Long")
JsError(p, e)
}
case (err, (k, v)) =>
// TODO: Accumulate errors...
err
}
}
}
implicit def longMapWrites[T](implicit w: Writes[T]): Writes[Map[Long, T]] = Writes[Map[Long, T]] { map =>
Json.toJson(map.map { case (k, v) =>
k.toString -> Json.toJson(v)(w)
})
}
implicit def longMapFormat[T](implicit r: Reads[T], w: Writes[T]): Format[Map[Long, T]] = Format(longMapReads,
longMapWrites)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment