使用Scala和Argonaut提取特定的JSON字段

时间:2015-01-29 12:27:00

标签: json scala argonaut

我正在尝试用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)

如何只能通过名称指定一个字段?

1 个答案:

答案 0 :(得分:1)

您的代码有:

implicit def AddressCodecJson: CodecJson[Address] =
  casecodec2(Address.apply, Address.unapply)("headers", "rest")

你说:

  

我将val userData: Option[Address] = parse(content) println(s"Extracted IP address = ${userData.get.headers}")替换为println(content)并获取:{ "Host": "headers.jsontest.com", "User-Agent": "Dispatch/0.11.1-SNAPSHOT", "Accept": "/" }

所以你的反应是:

{ "Host": "headers.jsontest.com", "User-Agent": "Dispatch/0.11.1-SNAPSHOT", "Accept": "/" }

你正在解码它:

Parse.decodeOption[UserData](data).get

...这意味着你肯定很明显地回到None

- 现在为什么您希望从不包含预期Noneheaders属性的JSON字典中获取非rest值?

(我假设您知道在.get上调用Option[T]并保留None值会引发异常。)

P.S。我不确定HTTP地址与地址有什么关系......?只是说......从建模的角度来看。