如何使用Play Framework JSON库为Map [Int,Int]创建JSON格式? [英] How do I create a JSON format for Map[Int, Int] using Play Framework JSON libs?
问题描述
我想使用Play Framework JSON库序列化Map[Int, Int]
.我想要类似的东西
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]]
import play.api.libs.json._
implicit val formatIntMap = Json.format[Map[Int, Int]]
但是该代码得到了No unapply function found
,我认为这是因为Map
没有简单的案例类,所以没有提取器.
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.
推荐答案
它将尝试制作JsObject,但由于将String映射到JsValue而不是将Int映射到JsValue而失败.您需要告诉它如何将密钥转换为字符串.
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)
}
}
这会将包含0-> 123的Map [Int,Int]转换为
This will turn a Map[Int, Int] containing 0 -> 123 into
JsObject(
Seq(
("0", JsNumber(123))
)
)
这篇关于如何使用Play Framework JSON库为Map [Int,Int]创建JSON格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!