This should do it, with the caveat that it doesn't handle NumberFormatException
in the reads
case:
//
// scala> Json.toJson(Map(1 -> 2L, 2 -> 3L))
// res0: play.api.libs.json.JsValue = {"1":2,"2":3}
//
implicit val formatter: Format[Map[Int, Long]] = {
new Format[Map[Int, Long]] {
def writes(m: Map[Int, Long]) = {
Json.toJson(m.map {
case (key, value) => key.toString -> value
})
}
def reads(json: JsValue) = {
json.validate[Map[String, Long]].map(_.map {
case (key, value) => key.toInt -> value
})
}
}
}
As separate Reads
and Writes
instances:
implicit val readsInstance: Reads[Map[Int, Long]] = {
new Reads[Map[Int, Long]] {
def reads(json: JsValue) = {
json.validate[Map[String, Long]].map(_.map {
case (key, value) => key.toInt -> value
})
}
}
}
implicit val writesInstance: Writes[Map[Int, Long]] = {
def writes(m: Map[Int, Long]) = {
Json.toJson(m.map {
case (key, value) => key.toString -> value
})
}
}
}