Scala play Json-使用类型参数读取转换器

问题描述 投票:0回答:1

我想用这样的类型参数创建一个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 [GeneralReadsT​​ype]的Json解串器。尝试为此类型实现隐式的Reads或Format。

所以,应该如何实现?

谢谢!

scala playframework
1个回答
0
投票
我发现最好将格式对象作为隐式字段放置在对象本身(或case类的伴随对象中)中。同样,当对Enumeration对象使用Enumeration复数形式,而对值使用单数形式时,则使其读起来更好。因此:

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

© www.soinside.com 2019 - 2024. All rights reserved.