本文介绍了找不到Seq [(String,String)]类型的Json序列化器.尝试为此类型实现隐式的Writes或Format的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过Scala播放将Seq[(String, String)]
转换为JSON,但我遇到此错误:
I want to convert a Seq[(String, String)]
into JSON with Scala play, but I face this error:
我该如何解决?
推荐答案
这取决于您要实现的目标.假设您有这样的Seq[(String, String)]
:
It depends on what you're trying to achieve. Say you have a Seq[(String, String)]
like this:
val tuples = Seq(("z", "x"), ("v", "b"))
如果您尝试按以下方式进行序列化:
If you are trying to serialize it as following:
{
"z" : "x",
"v" : "b"
}
然后只需使用Json.toJson(tuples.toMap)
.如果您希望对元组进行一些自定义表示,则可以按照编译器的建议定义Writes
:
Then just use Json.toJson(tuples.toMap)
. If you'd like to have some custom representation of your tuples you can define a Writes
as the compiler suggests:
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))
}
}
这篇关于找不到Seq [(String,String)]类型的Json序列化器.尝试为此类型实现隐式的Writes或Format的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!