gpt4 book ai didi

json - 未找到 Seq[(String, String)] 类型的 Json 序列化程序。尝试为这种类型实现隐式写入或格式

转载 作者:行者123 更新时间:2023-12-04 22:12:07 25 4
gpt4 key购买 nike

我想使用 Scala play 将 Seq[(String, String)] 转换为 JSON,但我遇到了这个错误:

No Json serializer found for type Seq[(String, String)]. Try to implement an implicit Writes or Format for this type.



我怎样才能解决这个问题?

最佳答案

这取决于您要实现的目标。假设你有一个这样的 Seq[(String, String)]:

val tuples = Seq(("z", "x"), ("v", "b"))

如果您尝试将其序列化如下:
{
"z" : "x",
"v" : "b"
}

然后只需使用 Json.toJson(tuples.toMap) 。如果您想对元组进行一些自定义表示,您可以按照编译器的建议定义 Writes:
implicit val writer = new Writes[(String, String)] {
def writes(t: (String, String)): JsValue = {
Json.obj("something" -> t._1 + ", " + t._2)
}
}

编辑 :
import play.api.mvc._
import play.api.libs.json._

class MyController extends Controller {
implicit val writer = new Writes[(String, String)] {
def writes(t: (String, String)): JsValue = {
Json.obj("something" -> t._1 + ", " + t._2)
}
}

def myAction = Action { implicit request =>
val tuples = Seq(("z", "x"), ("v", "b"))
Ok(Json.toJson(tuples))
}
}

关于json - 未找到 Seq[(String, String)] 类型的 Json 序列化程序。尝试为这种类型实现隐式写入或格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25681091/

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