Last active
August 24, 2017 16:18
-
-
Save joost-de-vries/52e019755f4f87f8ec2d9b9718a9bcad to your computer and use it in GitHub Desktop.
Play Json Map[K,V]
This file contains hidden or 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
| /** Play Json only supports Map[String,V]. This function creates a format for Map[K,V]. The type K should produce a JsString. | |
| * Otherwise the serialisation will fail. Which is good enough since in valid json keys can only be strings. */ | |
| def mapFormat[K, V](implicit fk: Format[K], fv: Format[V]): Format[Map[K, V]] = new OFormat[Map[K, V]] { | |
| override def writes(o: Map[K, V]): JsObject = { | |
| val stringMap = o.map { case (k, v) => (Json.toJson[K](k).as[JsString].value, v) } | |
| Json.toJson(stringMap).as[JsObject] | |
| } | |
| override def reads(json: JsValue): JsResult[Map[K, V]] = { | |
| for { | |
| stringMap <- Json.fromJson[Map[String, V]](json) | |
| _ <- Json.fromJson[Set[K]](Json.toJson(stringMap.keySet)) | |
| } yield stringMap.map { case (k, v) => (Json.fromJson[K](JsString(k)).get, v) } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment