1

I have a json array like below which is fetched from a database column into scala

jsonArrayString = "[{"firstName": "Harry", "lastName": "Smith"}, {"firstName": "John", "lastName": "Ken"}]"

I want to iterate through this array and get the values of dictionary keys in a for loop.

Thanks much for your help!

  • 1
    Define a case class like `final case class User(firstName: String, lastName: String)` and use any of the plenty **Json** libraries to parse that string tino a `List[User]` then you can process that list using `map`, `foreach`, etc. – Luis Miguel Mejía Suárez Sep 23 '20 at 21:19

3 Answers3

1

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.

gabeg
  • 149
  • 2
0

This question is very broad. There are numerous JSON parsing libraries in Scala, which make this a trivial task. They will all deserialize a JSON array to a scala list of whatever type you decode it to. Since you are dealing with a product, you can choose to use any Product type such as a builtin Tuple or a custom class. Personally I am partial to Circe https://github.com/circe/circe

YisraelU
  • 352
  • 1
  • 8
0
libraryDependencies += "org.json" % "json" % "20200518"

This is helpful for Json iteration.

Samual
  • 67
  • 9