简体   繁体   中英

Extracting string from JSON using Json4s using Scala

I have a JSON body in the following form:

val body = 
{
    "a": "hello",
    "b": "goodbye"
}

I want to extract the VALUE of "a" (so I want "hello") and store that in a val. I know I should use "parse" and "Extract" (eg. val parsedjson = parse(body).extract[String]) but I don't know how to use them to specifically extract the value of "a"

To use extract you need to create a class that matches the shape of the JSON that you are parsing. Here is an example using your input data:

val body ="""
{
  "a": "hello",
  "b": "goodbye"
}
"""

case class Body(a: String, b: String)

import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = DefaultFormats

val b = Extraction.extract[Body](parse(body))

println(b.a) // hello

You'd have to use pattern matching/extractors:

val aOpt: List[String] = for {
  JObject(map) <- parse(body)
  JField("a", JString(value)) <- map
} yield value

alternatively use querying DSL

parse(body) \ "a" match {
  case JString(value) => Some(value)
  case _              => None
}

These are options as you have no guarantee that arbitrary JSON would contain field "a" .

See documentation

extract would make sense if you were extracting whole JObject into a case class .

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