问题
This is my Search Object:
package models.helper
import play.api.libs.json.Format
import play.api.libs.json.JsValue
import play.api.libs.json.JsObject
import play.api.libs.json.JsString
case class Search (name: String, `type`:String){
implicit object SearchFormat extends Format[Search] {
def reads(json: JsValue): Search = Search(
(json \ "name").as[String],
(json \ "type").as[String]
)
def writes(s: Search): JsValue = JsObject(Seq(
"name" -> JsString(s.name),
"type" -> JsString(s.`type`)
))
}
}
I'm trying ot use this class when calling a webservice using WS:
val search = response.json.as[Search]
But the scala compiler keeps complaining on this line:
No Json deserializer found for type models.helper.Search. Try to implement an implicit Reads or Format for this type.
Could anybody tell me what I'm doing wrong?
- got the example from https://sites.google.com/site/play20zh/scala-developers/working-with-json
- this thread discusses the same issue but gives no solution, what example on what site? https://groups.google.com/forum/?fromgroups#!topic/play-framework/WTZrmQi5XxY
回答1:
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]
来源:https://stackoverflow.com/questions/10488950/play2-does-not-find-my-implicit-reads-or-format-for-json