Scala 无法为JSON创建隐式读取
我的服务器代码将接收以下Scala 无法为JSON创建隐式读取,scala,playframework-2.6,Scala,Playframework 2.6,我的服务器代码将接收以下JSON { "signin-info":{ "email" : "someemail", "password": "password" } } 我创建了以下两个案例类来表示这个结构 case class UserSigninInfo( email:String, password:String ) case class UserSignin( signinInfo: UserSigninInfo ) 为了阅
JSON
{
"signin-info":{
"email" : "someemail",
"password": "password"
}
}
我创建了以下两个案例类来表示这个结构
case class UserSigninInfo(
email:String,
password:String
)
case class UserSignin(
signinInfo: UserSigninInfo
)
为了阅读JSON,我创建了以下2个Reads
implicit val userSigninInfoReads:Reads[UserSigninInfo] = (
(JsPath \ "email").read[String] and
(JsPath \ "password").read[String]
)(UserSigninInfo.apply _)
implicit val userSigninReads:Reads[UserSignin] = (
(JsPath \ "signin-info").read[UserSigninInfo]
)(UserSignin.apply _)
但是对于userSigninReads
,我得到了以下编译错误。我做错了什么
overloaded method value read with alternatives:
[error] (t: models.UserSigninInfo)play.api.libs.json.Reads[models.UserSigninInfo] <and>
[error] (implicit r: play.api.libs.json.Reads[models.UserSigninInfo])play.api.libs.json.Reads[models.UserSigninInfo]
[error] cannot be applied to (models.UserSigninInfo => models.UserSignin)
[error] (JsPath \ "signin-info").read[UserSigninInfo]
[error] `
重载方法值,读取时使用替代项:
[error](t:models.UserSigninInfo)play.api.libs.json.Reads[models.UserSigninInfo]
[error](隐式r:play.api.libs.json.Reads[models.UserSigninInfo])play.api.libs.json.Reads[models.UserSigninInfo]
[错误]无法应用于(models.UserSigninInfo=>models.UserSignin)
[错误](JsPath\“登录信息”)。读取[用户登录信息]
[错误]`
为主要对象构造读取的解决方案是:
implicit val userSigninReads : Reads[UserSignin] =
(JsPath \ "signin-info").read[UserSigninInfo].map(UserSignin(_))
这是因为它只有一个字段
你的建筑本质上是:
((JsPath \ "signin-info").read[UserSigninInfo])(UserSignin.apply _)
这很简单
(JsPath \ "signin-info").read[UserSigninInfo](UserSignin.apply _)
因为它只是添加了额外的()
read
方法确实有两种选择:
def read[T](t: T) = Reads.pure(t)
def read[T](implicit r: Reads[T]): Reads[T] = Reads.at[T](this)(r)
它需要隐式读取或显式值,但您正在传递函数,这就是编译器抱怨的原因
当您将多个字段与和
组合时,会创建不同的对象,例如FunctionalBuilder[M]#可以为2个元素构建2[A,B]
,并且它具有应用
方法来构建最终的读取
实例
由于您只有一个对象,您可以通过从所需路径读取
UserSigninInfo
并使用map
将结果放入UserSignin
来创建您的Reads
,谢谢。我去查一下。我确实注意到,如果我添加另一个字段并使用和
,代码就会起作用。但我不明白其中的逻辑。期待您的进一步解释谢谢。成功了。所以(JsPath\“signin info”).read[UserSigninInfo]
返回Reads[UserSigninInfo]
。的map
读取
返回一个类型为UserSigninInfo
的对象,该对象被传递到UserSigninInfo
(即读取[UserSigninInfo].map(x:UserSigninInfo=>UserSigninInfo.apply(s))
?我不会完全使用这些词,但基本上是肯定的(除了我猜您上一段代码中的输入错误外,apply
部分中不应该有信息)。map
是一个可以将Reads[a]
转换为Reads[B]的函数
给定A=>B
。因此map使用函数UserSigninInfo=>UserSignin
map
允许我们获得UserSigninInfo
对象,这样我们就可以将其包装成UserSignin
,从而产生读取[UserSignin]。