json - Play Map[Int,_] 的 JSON 格式化程序

标签 json scala playframework playframework-2.3

我正在尝试使用 play-reactivemongo 和reactivemongo-extensions 将Rails/Mongodb 应用程序迁移到Play 2.3。在对数据建模时,我遇到了序列化和反序列化 Map[Int,Boolean] 的问题。

当我尝试通过宏定义我的格式时

implicit val myCaseClass = Json.format[MyCaseClass]

其中 MyCaseClass 有几个字符串字段、一个 BSONObjectID 字段和一个 Map[Int,Boolean] 字段,编译器会提示:
No Json serializer found for type Map[Int,Boolean]. Try to implement an implicit Writes or Format for this type.
No Json deserializer found for type Map[Int,Boolean]. Try to implement an implicit Reads or Format for this type.

查看 Reads.scala 中 Play 的源代码,我看到为 Map[String,_] 定义的读取,但没有为 Map[Int,_] 定义的读取。

为什么 Play 对字符串映射有默认读/写,但对其他简单类型没有?

我不完全理解 play 定义的 Map[String,_] ,因为我对 Scala 还很陌生。我将如何将其翻译成 Map[Int,_]?如果由于某些技术原因这是不可能的,我将如何定义 Map[Int,Boolean] 的读/写?

最佳答案

您可以在游戏中编写自己的读写操作。

在你的情况下,这看起来像这样:

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)

我已经用 play 2.3 测试过了。不过,我不确定在服务器端使用 Map[Int, Boolean] 和在客户端使用字符串 -> bool 映射的 json 对象是否是最佳方法。

关于json - Play Map[Int,_] 的 JSON 格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27285760/

相关文章:

java - 尝试运行 Google 语音识别 java 示例时出现 "need path to queries.json"错误

json - 当 json 元素不存在时,如何设置 spray-json 以设置 null?

json - 如何更改 golang 标签的默认操作?

java - 使用 setParameter 进行 ebean 查询

playframework - Play 框架的维护模式

XML::XML2JSON "0"元素

java - Play 2 框架 : scala iterate through fields of java objects in view

scala - 从 Spark 数据框中提取列值并将其添加到另一个数据框中

scala - Scala Web微框架

playframework - Play 框架模板参数 - 传递一个子类