重载的方法值[read]无法应用于(String => SearchController.this.TrackSearch)

时间:2016-11-18 14:29:43

标签: json scala playframework

我正在使用ws查询spotify api以查找给定查询的曲目列表,当我将JSON数据转换为案例类时我得到的错误是我'还没弄明白...

class SearchController @Inject() (
  val ws: WSClient
    ) extends Controller {

  case class TrackSearch(href: String)

  implicit val trackResultsReads: Reads[TrackSearch] = (
      (__ \ "tracks" \ "href").read[String]
    )(TrackSearch.apply _)

  def index = Action.async { implicit request =>
    search("track", param(request, "q")).map { r =>
       val ts = r.json.as[TrackSearch]
       println(ts)
       Ok
    }
  }

  private def search(category: String, query: String): Future[Try[WSResponse]] = {
    ws.url("https://api.spotify.com/v1/search")
      .withQueryString("q" -> query, "type" -> category)
      .get()
      .map(Success(_))
      .recover { case x => Failure(x) }
  }

  private def param(request: Request[AnyContent], name: String): String = {
    request.queryString.get(name).flatMap(_.headOption).getOrElse("")
  }
}

我得到的错误是:

Overloaded method value [read] cannot be applied to  (String => SearchController.this.TrackSearch)

  implicit val trackResultsReads: Reads[TrackSearch] 
>    (__ \ "tracks" \ "href").read[String]
  )(TrackSearch.apply _)

如果我在动作中查询JSPath,我可以得到" href"字符串返回正常,所以不是这样:

println(r._2.json \ "tracks" \ "href")

1 个答案:

答案 0 :(得分:5)

问题在于只有一个字段。如果你添加了第二个字段,它将编译。我不完全理解为什么它不应该用单个字段编译。因此,在单场案例中,请尝试以下方法:

implicit val trackResultsReads: Reads[TrackSearch] = {
  ((__ \ "tracks" \ "href").read[String])
    .map(TrackSearch(_))
}

Here是一个相当古老的链接,我发现了上述内容。有关具有不同方法的类似SO问题,另请参阅this link