我正在尝试使用 Scala 和 Argonaut 解析 json。
假设我从另一端 REST 服务获得 JSON 响应,并且我不知道该响应中 json 字段的顺序和字段数。例如,http://headers.jsontest.com/返回带有五个字段的 JSON,但我只想提取一个字段并删除其他字段:
{
"Accept-Language": "ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3",
"Host": "headers.jsontest.com",
"Referer": "http://www.jsontest.com/",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.4.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
所以我写了一些代码:
object Service {
case class Address(headers: String, rest: Option[String])
implicit def AddressCodecJson: CodecJson[Address] =
casecodec2(Address.apply, Address.unapply)("headers", "rest")
def parse(data: String): Option[Address] = {
Parse.decodeOption[Address](data)
}
def main(args: Array[String]): Unit = {
val src = url("http://headers.jsontest.com/")
val response: Future[String] = Http(src OK as.String)
response onComplete {
case Success(content) => {
val userData: Option[Address] = parse(content)
println(s"Extracted IP address = ${userData.get.headers}")
}
case Failure(err) => {
println(s"Error: ${err.getMessage}")
}
}
}
}
但是当然这段代码不起作用,可能是因为来自 jsontest 的答案不能与Address
案例类进行比较。
我收到此错误消息:
java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:313)
at scala.None$.get(Option.scala:311)
at micro.api.Service$$anonfun$main$1.apply(Service.scala:26)
at micro.api.Service$$anonfun$main$1.apply(Service.scala:23)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
at scala.concurrent.impl.ExecutionContextImpl$$anon$3.exec(ExecutionContextImpl.scala:107)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.pollAndExecAll(ForkJoinPool.java:1253)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1346)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
我怎样才能只获得其名称指定的一个字段?