Play2 does not find my implicit Reads or Format for JSON

只愿长相守 提交于 2019-12-05 05:43:10

Indeed the example is wrong. You need your implicit Format[Search] value to be available in the implicit scope.

In your case the Format[Search] is defined as a nested value of the class Search, so you can reach it only from an instance of Search.

So, what you want to do is to define it in another place, where it could be referenced without having to create an instance of Search, e.g. in a Formats object:

object Formats {
  implicit SearchFormat extends Format[Search] {
    …
  }
}

Then you can use it as follows:

import Formats.SearchFormat
val search = response.json.as[Search]

You can also get rid of the import tax by defining the Format[Search] value in the companion object of the Search class. Indeed the Scala compiler automatically looks in companion objects of type parameters when it needs an implicit value of a given type:

case class Search(name: String, `type`: String)

object Search {
  implicit object SearchFormat extends Format[Search] {
    …
  }
}

Then you can use it without having to import it:

val search = response.json.as[Search]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!