1

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.

2 Answers 2

4

Something like this should do:

val objects = (0 until jsonArray.length).map(jsonArray.getJSONObject)
Sign up to request clarification or add additional context in comments.

2 Comments

And what kind of data structure is "objects"? How can I now get the "value" item from that object?
objects is a list of JSONObject. I am not sure what you mean by "value item".
1

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")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.