简体   繁体   中英

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 [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?

You can you 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 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM