Play JSON formatter for Map[Int,_]

后端 未结 6 1370
自闭症患者
自闭症患者 2020-12-29 11:41

I am attempting to migrate a Rails/Mongodb application to Play 2.3 using play-reactivemongo and reactivemongo-extensions. In modeling my data I am running across a problem s

6条回答
  •  别那么骄傲
    2020-12-29 12:11

    you can write your own reads and writes in play.

    in your case, this would look like this:

    implicit val mapReads: Reads[Map[Int, Boolean]] = new Reads[Map[Int, Boolean]] {
        def reads(jv: JsValue): JsResult[Map[Int, Boolean]] =
            JsSuccess(jv.as[Map[String, Boolean]].map{case (k, v) =>
                Integer.parseInt(k) -> v .asInstanceOf[Boolean]
            })
    }
    
    implicit val mapWrites: Writes[Map[Int, Boolean]] = new Writes[Map[Int, Boolean]] {
        def writes(map: Map[Int, Boolean]): JsValue =
            Json.obj(map.map{case (s, o) =>
                val ret: (String, JsValueWrapper) = s.toString -> JsBoolean(o)
                ret
            }.toSeq:_*)
    }
    
    implicit val mapFormat: Format[Map[Int, Boolean]] = Format(mapReads, mapWrites)
    

    I have tested it with play 2.3. I'm not sure if it's the best approach to have a Map[Int, Boolean] on server side and a json object with string -> boolean mapping on the client side, though.

提交回复
热议问题