如何从 Scala 中的 JSON 中的键中获取特定值?

我想从 url 下面的 JSON 中"stations"的键返回值。我如何在 Scala 中做到这一点?"base"https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22


这是我尝试的。


import scalaj.http._

import play.api.libs.json.{JsValue, Json}


object JSON {

def convertToJson(): String = {

    val url: String = "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22"

    val response: String = Http(url).asString.body

    val parsed: JsValue = Json.parse(response)

    parsed.get(base)

}

}


慕工程0101907
浏览 120回答 1
1回答

慕桂英4014372

您可以使用\方法返回对应于字段名称的属性val result: JsLookupResult = parsed \ "base"如果您希望结果为字符串,您可以使用as[String]转换println(result.as[String])它将打印“站”,但如果它不是真正的字符串,它会抛出异常如果缺少值,您可以使用模式匹配:result match {  case JsDefined(v) => println(v.toString) // will print "stations"  case undefined: JsUndefined => println(undefined.validationError) // prints error in case missing value}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java