Reputation: 85
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!
Upvotes: 2
Views: 2761
Reputation: 67
libraryDependencies += "org.json" % "json" % "20200518"
This is helpful for Json iteration.
Upvotes: 0
Reputation: 372
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
Upvotes: 1
Reputation: 139
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
.
Upvotes: 1