CallMeDeftsu4
CallMeDeftsu4

Reputation: 127

Iterate JSONArray in Scala

I'm pretty new to the Scala language, so I need some help here.

I have this JSONArray (org.json is the name of the package):

[{"id":"HomePDA"},{"id":"House2"},{"id":"House"},{"id":"7c587a4b-851d-4aa7-a61f-dfdae8842298","value":"xxxxxxxxxxx"},{"id":"Home"}]

If this was in java, I could solve this using the "foreach" structure, but I can't find something similar to that structure. I only need to get the JSONObjects from this array.

Is that possible or do I need to change the data structure? I prefer the first option, the second one is a little mess.

Thank you in advance.

Upvotes: 1

Views: 6208

Answers (2)

bmateusz
bmateusz

Reputation: 237

I would introduce a class House to help extracting the data.

import org.json._
import scala.util.{Try, Success, Failure}

case class House(id: String, value: String)

val jsonArray = new JSONArray("""[
{"id":"HomePDA"},
{"id":"House2"},
{"id":"House"},
{"id":"7c587a4b-851d-4aa7-a61f-dfdae8842298", "value":"xxxxxxxxxxx"},
{"id":"Home"}]""")

val objects = (0 until jsonArray.length).map(jsonArray.getJSONObject)

val houses = objects.map(s => Try(House(s.getString("id"), s.getString("value"))))

houses.foreach {
  case Success(house) => println(house.value)
  case Failure(exception) => Console.err.println(s"Error: $exception")
}

Upvotes: 1

Dima
Dima

Reputation: 40508

Something like this should do:

val objects = (0 until jsonArray.length).map(jsonArray.getJSONObject)

Upvotes: 4

Related Questions