作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在使用 Scala 的 Play Framework 中,如何将 String 和 Seq[String] 值的映射转换为 JSON 格式?以下代码对我产生错误:
val objMap = Map("id" -> "id", "tags" -> Seq("tag1", "tag2"))
Json.toJson(objMap)
产生的错误:
No Json serializer found for type scala.collection.immutable.Map[String,Object]. Try to implement an implicit Writes or Format for this type.
最佳答案
正如错误所述,您需要为 Map[String,Object]
实现 Writes
这是它的样子。我已经编译了这段代码,看起来不错。 (我假设您正在使用 Play 框架)。仅供引用:那里的案例仅供引用。您可以根据需要在其中添加/修改更多的 case
。
import play.api.libs.json._
import play.api.libs.json.Writes
import play.api.libs.json.Json.JsValueWrapper
val objMap = scala.collection.immutable.Map("id" -> "id", "tags" -> Seq("tag1", "tag2"))
Json.toJson(objMap)
implicit val writeAnyMapFormat = new Writes[Map[String, Object]] {
def writes(map: Map[String, Object]): JsValue = {
Json.obj(map.map {
case (s, a) => {
val ret: (String, JsValueWrapper) = a match {
case _: String => s -> JsString(a.asInstanceOf[String])
case _: java.util.Date => s -> JsString(a.asInstanceOf[String])
case _: Integer => s -> JsString(a.toString)
case _: java.lang.Double => s -> JsString(a.toString)
case None => s -> JsNull
case JsArray(elements) => s -> JsArray(elements)
case _ => s -> JsArray(a.asInstanceOf[List[Int]].map(JsNumber(_)))
}
ret
}
}.toSeq: _*)
}
}
关于json - 如何将由 String 和 Seq[String] 值组成的 Scala Map 转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24089192/
我是一名优秀的程序员,十分优秀!