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
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 classSearch
, so you can reach it only from an instance ofSearch
.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 aFormats
object:Then you can use it as follows:
You can also get rid of the import tax by defining the
Format[Search]
value in the companion object of theSearch
class. Indeed the Scala compiler automatically looks in companion objects of type parameters when it needs an implicit value of a given type:Then you can use it without having to import it: