我是Scala的新手,我正在学习Scala和Play Framework:我试图通过使用Map(...)
,List(...)
和Json.toJson(...)
从一系列名为"表"的数据开始动态创建play/scala的JSON。我的结果应该像下面显示的代码resultCustomJsonData
var resultCustomJsonData = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
nodes: [
{
text: "Grandchild 1"
},
{
text: "Grandchild 2"
}
]
},
{
text: "Child 2"
}
]
},
{
text: "Parent 2"
},
{
text: "Parent 3"
},
{
text: "Parent 4"
},
{
text: "Parent 5"
}
];
我的Scala代码是以下:
val customJsonData = Json.toJson(
tables.map { t => {
Map(
"text" -> t.table.name.name, "icon" -> "fa fa-cube", "nodes" -> List (
Map( "text" -> "properties" )
)
)
}}
)
但是我遇到了这个错误:
No Json serializer found for type Seq[scala.collection.immutable.Map[String,java.io.Serializable]]. Try to implement an implicit Writes or Format for this type.
这是一种不使用临时Map
的方法
import play.api.libs.json.Json
val customJsonData = Json.toJson(
tables.map { t =>
Json.obj(
"text" -> t.table.name.name,
"icon" -> "fa fa-cube",
"nodes" -> Json.arr(Json.obj("text" -> "properties"))
)
}
)
我认为您应该尝试实现自定义序列化器/作者。在这里检查。
例如:
implicit val userWrites = new Writes[User] {
def writes(user: User) = Json.obj(
"id" -> user.id,
"email" -> user.email,
"firstName" -> user.firstName,
"lastName" -> user.lastName
)
}