logo

Scala - json4s

Official Website

In sbt:

libraryDependencies += "org.json4s" %% "json4s-jackson" % "3.2.10"

parse:

val source = scala.io.Source.fromFile("/path/to/file.json")

val json = JsonMethods.parse(source.reader())

extract value

if json is an object

val value = json \ "key"

if json is a list, get the first element:

val firstElement = json(0)

extract as String

val v: String = value.extract[String]
val content: String = Source.fromFile(path).mkString
val parsed = JsonMethods.parse(content)
val obj = parsed.extract[MyClass]

With Custom Serializer

class MySerializer extends CustomSerializer[Double](format => ( {
  case JString("NaN") => Double.NaN
  case JString("-Infinity") => Double.NegativeInfinity
  case JString("Infinity") => Double.PositiveInfinity
}, {
  case Double.NaN => JString("NaN")
  case Double.NegativeInfinity => JString("-Infinity")
  case Double.PositiveInfinity => JString("Infinity")
}
  ))
val content: String = Source.fromFile(path).mkString
val parsed = JsonMethods.parse(content)
implicit val formats = Serialization.formats(NoTypeHints) + new MySerializer
val obj = parsed.extract[MyClass]

Trouble Shooting

Error:

No org.json4s.Formats found. Try to bring an instance of org.json4s.Formats in scope or use the org.json4s.DefaultFormats.

Solution: add this

implicit val formats = DefaultFormats