gpt4 book ai didi

json - 如何将由 String 和 Seq[String] 值组成的 Scala Map 转换为 JSON?

转载 作者:行者123 更新时间:2023-12-05 01:16:28 25 4
gpt4 key购买 nike

在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com