【问题标题】:No Instance of play.api.libs.json.Format is availablefor scala.collection.immutable.List[Item]scala.collection.immutable.List[Item] 没有 play.api.libs.json.Format 的实例
【发布时间】:2019-06-25 15:23:21
【问题描述】:

注意:我对 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)
    }
}

【问题讨论】:

    标签: scala playframework play-json


    【解决方案1】:

    在您的代码中,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}]}
    

    【讨论】:

    • 我试过了,但我收到了完全相同的错误
    • @Chris 你把他们都放在同一个文件里了吗?
    • Walkar 是的,我把 object Item {...} 放在除了导入之外的所有内容之前
    • 当我将隐式 val 语句放入 ItemREST 对象而不是 Item 对象时,它起作用了。感谢您的帮助!
    • 这就是我现在要建议的。我刚刚在我的 IDE 中尝试了该代码并将其粘贴到此处。无论如何,这对你来说很好。我正在编辑我的答案,请接受它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2021-10-12
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2020-06-30
    • 2017-09-12
    相关资源
    最近更新 更多