【问题标题】:Scala Play Json JSResultException Error APIScala Play Json JSResultException 错误 API
【发布时间】:2017-12-21 02:25:31
【问题描述】:

我正在尝试从我从 API Rest (Swagger) 获得的 json 内容中获取嵌套值。我想访问第一个“url”值:

  val getFeedVersionURL =  url("https://api.transitfeeds.com/v1/getFeedVersions?").GET <<? List(
    "key" -> someKey,
    "feed" -> "consorcio-regional-de-transportes-de-madrid/743",
    "page" -> "1",
    "limit" -> "10000",
    "err" -> "1 (default)",
    "warn" ->"1 (default)")

  val response : Future[String] = Http.configure(_ setFollowRedirects true)(getFeedVersionURL OK as.String)

  val src: String = getFeedVersionURL.toString()

  response onComplete {
    case Success(content) => {
      println("Successful response" + content)

      //Parse the content
      val jsonObject = Json.parse(content)
      //Get url value
      val fileDownloadURL = (jsonObject \ "results" \ "versions" \ "url").as[String]
      //Save the file
      new URL(fileDownloadURL) #> new File("C:/Users//Desktop//file.zip") !!


    }
    case Failure(t) => {
      println("An error has occured: " + t.getMessage)
    }
  }

这是我收到的 json:

{
  "status": "OK",
  "ts": 1513600944,
  "results": {
    "total": 4,
    "limit": 100,
    "page": 1,
    "numPages": 1,
    "versions": [
      {
        "id": "consorcio-regional-de-transportes-de-madrid/743/20171127",
        "f": {
          "id": "consorcio-regional-de-transportes-de-madrid/743",
          "ty": "gtfs",
          "t": "Metro Ligero de Madrid GTFS",
          "l": {
            "id": 167,
            "pid": 166,
            "t": "Madrid, Spain",
            "n": "Madrid",
            "lat": 40.416775,
            "lng": -3.70379
          },
          "u": {
            "i": "http://crtm.maps.arcgis.com/home/item.html?id=aaed26cc0ff64b0c947ac0bc3e033196"
          }
        },
        "ts": 1511848526,
        "size": 403388,
        "url": "https://transitfeeds.com/p/consorcio-regional-de-transportes-de-madrid/743/20171127/download",
        "d": {
          "s": "20170106",
          "f": "20180629"
        },
        "err": [],
        "warn": []
      },
      {
        "id": "consorcio-regional-de-transportes-de-madrid/743/20170927",
        "f": {
          "id": "consorcio-regional-de-transportes-de-madrid/743",
          "ty": "gtfs",
          "t": "Metro Ligero de Madrid GTFS",
          "l": {
            "id": 167,
            "pid": 166,
            "t": "Madrid, Spain",
            "n": "Madrid",
            "lat": 40.416775,
            "lng": -3.70379
          },
          "u": {
            "i": "http://crtm.maps.arcgis.com/home/item.html?id=aaed26cc0ff64b0c947ac0bc3e033196"
          }
        },
        "ts": 1506554131,
        "size": 403052,
        "url": "https://transitfeeds.com/p/consorcio-regional-de-transportes-de-madrid/743/20170927/download",
        "d": {
          "s": "20170106",
          "f": "20180925"
        },
        "err": [],
        "warn": []
      },
      {
        "id": "consorcio-regional-de-transportes-de-madrid/743/20170526",
        "f": {
          "id": "consorcio-regional-de-transportes-de-madrid/743",
          "ty": "gtfs",
          "t": "Metro Ligero de Madrid GTFS",
          "l": {
            "id": 167,
            "pid": 166,
            "t": "Madrid, Spain",
            "n": "Madrid",
            "lat": 40.416775,
            "lng": -3.70379
          },
          "u": {
            "i": "http://crtm.maps.arcgis.com/home/item.html?id=aaed26cc0ff64b0c947ac0bc3e033196"
          }
        },
        "ts": 1495816290,
        "size": 408985,
        "url": "https://transitfeeds.com/p/consorcio-regional-de-transportes-de-madrid/743/20170526/download",
        "d": {
          "s": "20170106",
          "f": "20180526"
        },
        "err": [],
        "warn": []
      },
      {
        "id": "consorcio-regional-de-transportes-de-madrid/743/20161012",
        "f": {
          "id": "consorcio-regional-de-transportes-de-madrid/743",
          "ty": "gtfs",
          "t": "Metro Ligero de Madrid GTFS",
          "l": {
            "id": 167,
            "pid": 166,
            "t": "Madrid, Spain",
            "n": "Madrid",
            "lat": 40.416775,
            "lng": -3.70379
          },
          "u": {
            "i": "http://crtm.maps.arcgis.com/home/item.html?id=aaed26cc0ff64b0c947ac0bc3e033196"
          }
        },
        "ts": 1476308287,
        "size": 420670,
        "url": "https://transitfeeds.com/p/consorcio-regional-de-transportes-de-madrid/743/20161012/download",
        "d": {
          "s": "20160101",
          "f": "20170621"
        },
        "err": [],
        "warn": []
      }
    ]
  }
}

问题是我收到这个错误:

play.api.libs.json.JsResultException: JsResultException(errors:List((,List(ValidationError(error.expected.jsstring,WrappedArray())))))

有什么想法吗?

【问题讨论】:

  • "versions" \ "url" 期望 versions 是一个对象,而它是一个数组

标签: json scala playframework


【解决方案1】:

评论中的cchantep是正确的。您需要拔出versions 键并进行适当处理。这是一些非常粗略的代码,可以满足您的要求:

import play.api.libs.json._
val jsonObject = Json.parse(s) // s is that string you gave in your q

val fileDownloadURL: String = (jsonObject \ "results" \ "versions") match {
    case JsDefined(JsArray(versions)) => versions.headOption match {
        case Some(jsValue) => (jsValue \  "url").as[String]
        case _ => "NOPE hope you got some logic here"
    }
    case nope => throw new IllegalArgumentException("handle this better than this!")
}

我得到:

res0: String = https://transitfeeds.com/p/consorcio-regional-de-transportes-de-madrid/743/20171127/download

请注意,我在控制台中使用 play 2.4 执行此操作,对于 2.3 和其他版本可能存在差异。如果你提供你正在使用的游戏版本,我可能会给你一些关于如何完成你想要做的事情的粗略想法。

请注意,上面的匹配是一种方式,另一种方式是使用as一堆

val thisToo = (jsonObject \ "results" \ "versions").as[JsArray].value.headOption.map(first => (first \ "url").as[String]).getOrElse(throw new IllegalArgumentException("handle this better than this!"))

【讨论】:

  • 谢谢你的朋友,你的代码很棒而且可以工作。但是,如果我需要将该 json 的所有“url”字段保存在变量(列表)中怎么办?我试过 for bucle 但没有用。
  • 对于所有 URL,您可以将 .as[JsArray].value.headOption.map(first =&gt; (first \ "url").as[String]) 更改为 .as[JsArray].value.map(first =&gt; (first \ "url").as[String])
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多