Play2找不到我的隐式读取或JSON格式 [英] Play2 does not find my implicit Reads or Format for JSON

查看:126
本文介绍了Play2找不到我的隐式读取或JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的搜索对象:

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`)
    ))  
  }
}

我正在尝试使用WS调用Web服务时使用此类:

I'm trying ot use this class when calling a webservice using WS:

val search = response.json.as[Search]

但是scala编译器一直在抱怨这一行:

But the scala compiler keeps complaining on this line:

未找到用于model.helper.Search类型的Json反序列化器.尝试 为此类型实现隐式的Reads或Format.

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

推荐答案

实际上,该示例是错误的.您需要隐式Format[Search]值在隐式范围内可用.

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

在您的情况下,Format[Search]被定义为类Search的嵌套值,因此您只能从Search的实例获取它.

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.

因此,您想要做的是在另一个地方定义它,而不必创建Search的实例即可引用它,例如在Formats对象中:

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]

您还可以通过在Search类的伴随对象中定义Format[Search]值来摆脱进口税.实际上,当Scala编译器需要给定类型的隐式值时,它会自动查找类型参数的伴随对象:

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]

这篇关于Play2找不到我的隐式读取或JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆