播放ScalaJSON读取[T]解析类型不匹配错误

时间:2016-11-03 12:59:44

标签: json scala implicit-conversion

我有一大块Json,其中我只关心一小部分,例如:

{
  "request": {
    "c": {
      "code": "AA",
      "fsCode": "AA"
    },
    "codeType": {},
    "number": {
      "requested": "100",
     },
  "scheduled": [
    {
      "code": "BB",
      "number": "100",
      "classes": [
        "F",
        "Y"
      ]
   }]
}

我只想提取codenumber变量。我尝试使用Reads,如下所示:

case class TheResult(result: (String, String))

implicit val theScheduledReads: Reads[TheResult] = (
    (__ \ "code").read[String] and
      (__ \ "number").read[String] tupled) map TheScheduledFlight.apply _

case class ResultList(addr: List[TheResult])

implicit val resultReads: Reads[ResultList] =
  (__ \ "scheduled").read(List[TheResult](theScheduledReads)) map ResultList _

然后这将访问结果:

response.json.validate[List[ResultList]]

但是,它会抛出此错误:

type mismatch; found : play.api.libs.json.Reads[details.client.TheResult] required: details.client. TheResult (__ \ "address").read(List[TheResult](resultReads)) map (TheResult.apply _)

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:1)

修复了代码中的多个问题。看看

最重要的是read(List[TheResult](theScheduledReads))毫无意义。 它应该是read[List[TheResult]]

TheScheduledFlight.apply替换为TheResult.apply _

case class TheResult(result: (String, String))

implicit val theScheduledReads: Reads[TheResult] = (
  (__ \ "code").read[String] and
    (__ \ "number").read[String] tupled) map TheResult.apply _ //problem fixed here

case class ResultList(addr: List[TheResult])

implicit val resultReads: Reads[ResultList] =
  (__ \ "scheduled").read[List[TheResult]] map ResultList.apply _ //problem fixed here