How do I create a JSON format for Map[Int, Int] us

2019-08-26 11:00发布

问题:

I'd like to serialize a Map[Int, Int] using the Play Framework JSON libraries. I want something like

import play.api.libs.json._ implicit val formatIntMap = Json.format[Map[Int, Int]]

That code however gets an No unapply function found which I think is referring to the fact that there is no extractor for Map since it isn't a simple case class.

回答1:

It will try to make a JsObject but is failing as it maps a String to a JsValue, rather than an Int to a JsValue. You need to tell it how to convert your keys into Strings.

  implicit val jsonWrites = new Writes[Map[Int, Int]] {
    def writes(o: Map[Int, Int]): JsValue = {
      val keyAsString = o.map { kv => kv._1.toString -> kv._2} // Convert to Map[String,Int] which it can convert
      Json.toJson(keyAsString)
    }
  }

This will turn a Map[Int, Int] containing 0 -> 123 into

JsObject(
    Seq(
        ("0", JsNumber(123))
    )
)