Scala doesn't have any built-in JSON processing, so you'll need to use a third-party library. This answer lists Scala-specific libraries and any Java library would also work.
Even though it's not Scala-specific I usually use Jackson, when I'm working with JSON in Scala because it's usually already on the classpath in the apps I work in and it's a safe bet it will be supported well into the future because it's so widely used. It has an optional Scala module that adapts it to play well with Scala's built in types.
Here's one way to parse jsonArrayString
if Jackson and its Scala module are on your classpath:
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala._
case class Person(firstName : String, lastName : String)
val jackson = new ObjectMapper with ScalaObjectMapper
jackson.registerModule(DefaultScalaModule)
val jsonArrayString =
"""[{"firstName": "Harry", "lastName": "Smith"},
|{"firstName": "John", "lastName": "Ken"}]""".stripMargin
jackson.readValue[List[Person]](jsonArrayString).foreach { person =>
println(s"First Name: ${person.firstName}; Last Name: ${person.lastName}")
}
If either firstName
or lastName
could be null or absent, you can declare them with type Option[String]
and the Scala module will map null
to None
.