简体   繁体   中英

Extract specific JSON field with Scala and Argonaut

I'm trying to parse json with Scala and Argonaut.

Suppose I get JSON response from other side REST service and I don't know order of json's fields in that response and the number of fields. For example, http://headers.jsontest.com/ returns JSON with five fields, but I want to extract only one field and drop others:

{
   "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"
}

So I'm write some code:

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}")
      }
    }
  }
}

But of course this code doesn't work, probably because answers from jsontest doesn't compare with Address case class.

I get this error message:

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)

How can I get only one field specified by its name?

Your code has:

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

and you said:

I replace this lines: val userData: Option[Address] = parse(content) println(s"Extracted IP address = ${userData.get.headers}") with println(content) and get: { "Host": "headers.jsontest.com", "User-Agent": "Dispatch/0.11.1-SNAPSHOT", "Accept": "/" }

so the response you have is:

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

and you're decoding it like this:

Parse.decodeOption[UserData](data).get

...which means you're quite certainly and quite obviously getting back a None .

— now why would you be expecting to get a non- None value out of a JSON dictionary that does not contain the expected headers and rest attributes?

(I'm presuming you know that calling .get on an Option[T] that holds a None value throws an exception.)

PS I'm not sure what's an address got to do with HTTP headers...? Just sayin'... from a modelling point of view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM