Play JSON formatter for Map[Int,_]

后端 未结 6 1399
自闭症患者
自闭症患者 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:02

    Like the accepted answer - a bit shorter:

    implicit val mapReads: Reads[Map[Int, Boolean]] = (jv: JsValue) =>
        JsSuccess(jv.as[Map[String, Boolean]].map { case (k, v) =>
          k.toInt -> v
        })
    
    implicit val mapWrites: Writes[Map[Int, Boolean]] = (map: Map[Int, Boolean]) =>
        Json.toJson(map.map { case (s, o) =>
         s.toString -> o
        })
    
    implicit val jsonMapFormat: Format[Map[Int, Boolean]] = Format(mapReads, mapWrites)
    

    Here a little test:

    val json = Json.toJson(Map(1 -> true, 2 -> false))        
    println(json) // {"1":true,"2":false}
    println(json.validate[Map[Int, Boolean]]) // JsSuccess(Map(1 -> true, 2 -> false),)
    

提交回复
热议问题