jsonscalaplayframework-2.3

Render two json objects to the view with Play! scala 2.3


Here is a dumb question : I simply want to render two Json object to the view, I manage to do render them separately but not together...

I tried a simple trick like that (I tried with two '+' as well):

def totalToPay = Action { 
    Ok(Json.toJson(Account4686.findAllWithCredit()) + Json.toJson(Account403.findAllByOrgaIdWithCredit(1)))
}

but without success. I have this compilation error : [error] /home/sim/dev/ticketapp/app/controllers/Admin.scala:136: type mismatch; [error] found : play.api.libs.json.JsValue [error] required: String.

What is the correct way to perform this?


Solution

  • You can use the JsArray constructor that takes in a Seq[JsValue] as such:

    JsArray(Seq(Json.toJson(obj1), Json.toJson(obj2))
    

    Or if you want to use a JsObject instead of an array, you can do:

    Json.obj("obj1" -> obj1, "obj2" -> obj2)
    

    To merge two objects, you can use ++:

    Json.toJson(obj1).asInstanceOf[JsObject] ++ Json.toJson(obj2).asInstanceOf[JsObject]