1

I have in Scala an array array1 that contains, among other things, another array array2.

Now, I'm trying to replicate the structure in Json using Play. This is my attempt:

    var json = JsObject(Seq())
    array1.foreach(a1 => {
      json += "a1" -> JsNumber(a1.name) + 
      "a2" -> a1.array2.foreach {
        a2 => "a2" -> JsString(a2.name)
      }
    })

The error I'm getting is type mismatch; found : Unit required: play.api.libs.json.JsValue

How to fix this? thanks in advance.

2
  • Use map instead of foreach. foreach is for side-effect operations Commented Jul 10, 2016 at 11:43
  • Could you provide an example of how do your arrays look like? It would be easier to reproduce your error. Commented Jul 10, 2016 at 11:51

1 Answer 1

1

You probably want is to use map instead of foreach in the loops.

It's a little unclear as to what json you want, but based on the description of your objects, I'd say this is probably what you are a looking for:

val json =  JsArray(array1.map { a1 =>
  JsObject(List(
    "a1" -> JsNumber(a1.name),
    "a2" -> JsArray(a1.array2.map {
      a2 => JsString(a2.name)
    })
  ))
})
Sign up to request clarification or add additional context in comments.

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.