scala.collection.immutable.List[Item] 没有可用的 play.api.libs.json.Format 实例
No Instance of play.api.libs.json.Format is availablefor scala.collection.immutable.List[Item]
注意:我是 PlayFramework 的新手。
我正在尝试将项目对象序列化为 JSON 字符串。我收到以下错误:
No instance of play.api.libs.json.Format is available for
scala.collection.immutable.List[Item] in the implicit scope (Hint: if declared
in the same file, make sure it's declared before)
[error] implicit val itemRESTFormat: Format[ItemREST] =
Json.format[ItemREST]
我真的完全不明白这个错误是什么意思,也不知道哪里出了问题。如果有人可以向我解释错误的含义以及潜在的问题是什么,那就太好了。谢谢!
import...
case class ItemREST(items: List[Item]) {
def toJson: String = Json.toJson(this).as[JsObject].toString()
}
object ItemREST {
implicit val itemRESTFormat: Format[ItemREST] = Json.format[ItemREST]
def fromItem(items: List[Item]): ItemREST = {
ItemREST(items)
}
}
在您的代码中,ItemREST
具有 Item
类型的元素列表。因此,为了序列化 ItemREST
,需要 Item
的序列化器。
object Item {
implicit val itemFormat = Json.format[Item]
}
object ItemREST {
implicit val itemRESTFormat: Format[ItemREST] = Json.format[ItemREST]
}
你只需要在ItemREST之前声明Item的序列化器就可以解决你的问题。
此外,您可以尝试的一件事是添加
implicit val itemFormat = Json.format[Item]
就在
之前
implicit val itemRESTFormat: Format[ItemREST] = Json.format[ItemREST]
完整代码如下所示
case class Item(i : Int)
case class ItemList(list : List[Item])
object ItemList{
implicit val itemFormat = Json.format[Item]
implicit val itemListFormat = Json.format[ItemList]
}
object SOQ extends App {
println(Json.toJson(ItemList(List(Item(1),Item(2)))))
}
给你 n 个输出
{"list":[{"i":1},{"i":2}]}
注意:我是 PlayFramework 的新手。
我正在尝试将项目对象序列化为 JSON 字符串。我收到以下错误:
No instance of play.api.libs.json.Format is available for
scala.collection.immutable.List[Item] in the implicit scope (Hint: if declared
in the same file, make sure it's declared before)
[error] implicit val itemRESTFormat: Format[ItemREST] =
Json.format[ItemREST]
我真的完全不明白这个错误是什么意思,也不知道哪里出了问题。如果有人可以向我解释错误的含义以及潜在的问题是什么,那就太好了。谢谢!
import...
case class ItemREST(items: List[Item]) {
def toJson: String = Json.toJson(this).as[JsObject].toString()
}
object ItemREST {
implicit val itemRESTFormat: Format[ItemREST] = Json.format[ItemREST]
def fromItem(items: List[Item]): ItemREST = {
ItemREST(items)
}
}
在您的代码中,ItemREST
具有 Item
类型的元素列表。因此,为了序列化 ItemREST
,需要 Item
的序列化器。
object Item {
implicit val itemFormat = Json.format[Item]
}
object ItemREST {
implicit val itemRESTFormat: Format[ItemREST] = Json.format[ItemREST]
}
你只需要在ItemREST之前声明Item的序列化器就可以解决你的问题。
此外,您可以尝试的一件事是添加
implicit val itemFormat = Json.format[Item]
就在
之前 implicit val itemRESTFormat: Format[ItemREST] = Json.format[ItemREST]
完整代码如下所示
case class Item(i : Int)
case class ItemList(list : List[Item])
object ItemList{
implicit val itemFormat = Json.format[Item]
implicit val itemListFormat = Json.format[ItemList]
}
object SOQ extends App {
println(Json.toJson(ItemList(List(Item(1),Item(2)))))
}
给你 n 个输出
{"list":[{"i":1},{"i":2}]}