我想用这样的类型参数创建一个JSON reads转换器:
case class AClass(name: String, age: Int)
case class AClass(name: String)
object GeneralReadsType extends Enumeration {
type GeneralReadsType = Value
val AReadType = Value("atype")
val BReadType = Value("btype")
}
implicit val repoReads: Reads[GeneralReadsType.GeneralReadsType] = {
GeneralReadsType match {
case GeneralReadsType.AReadType => (
(JsPath \ "name").read[String] and
(JsPath \ "age").read[Int]
) (GeneralReadsType.AReadType.apply _)
case GeneralReadsType.BReadType => (
(JsPath \ "name").read[String]
) (GeneralReadsType.BReadType.apply _)
}
}
但是当我尝试使用它时
def getResponse[GeneralReadsType](request: WSRequest): Future[List[GeneralReadsType]] = {
request.get().map {
case response if response.status == 200 => {
(response.json).validate[List[GeneralReadsType]] match {
case JsSuccess(items: List[GeneralReadsType], _) => items
case _: JsError => List[GeneralReadsType]()
}
}
case _ => List[GeneralReadsType]()
}
}
getResponse[AReadType](request)
我收到编译错误
找不到类型为List [GeneralReadsType]的Json解串器。尝试为此类型实现隐式的Reads或Format。
所以,应该如何实现?
谢谢!
object GeneralReadsTypes extends Enumeration {
type GeneralReadsType = Value
val AReadType = Value("atype")
val BReadType = Value("btype")
implicit val repoReads: Reads[GeneralReadsType] = {
((JsPath \ "name").read[String] and
(JsPath \ "age").readNullable[Int]).apply { (_, maybeAge) =>
maybeAge.fold(BReadType)( _ => AReadType)
}
}
}
或者如果您发现功能样式太陌生:
object GeneralReadsTypes extends Enumeration { type GeneralReadsType = Value val AReadType = Value("atype") val BReadType = Value("btype") implicit val repoReads: Reads[GeneralReadsType] = { ((JsPath \ "name").read[String] and (JsPath \ "age").readNullable[Int]).apply { (_, maybeAge) => if (maybeAge.isDefined) AReadType else BReadType } } }