Amr Ragaey
Amr Ragaey

Reputation: 1093

Get some values from each object in Scala List of objects and send it to HTTP

I'm newbie in scala and play framework.I have a list of JSon objects, I'm trying to retrieve only two attributes (name and image) of each object in the list and send it in Json format to http response, I'm using mongoDB to get the full list

def NamesImages = Action.async {implicit request =>
val FutureProducts = productDao.find(BSONDocument()).collect[List]()
FutureProducts.map { prod => prod.map {
        a => 
        val prdObj = Json.obj("name" -> JsObject(a.name.get), "image" -> JsObject(a.image))
            Ok(new JsArray(Json.toJson(prdObj)))
        }
}}

I got compilation error:

 **type mismatch;**

 found   : play.api.libs.json.JsValue
 required: Seq[play.api.libs.json.JsValue]

Upvotes: 0

Views: 900

Answers (1)

axlpado - Agile Lab
axlpado - Agile Lab

Reputation: 353

You need to Wrap your result with a Seq. JsArray want a sequence of JsValue Try this:

    def NamesImages = Action.async {implicit request =>
val FutureProducts = productDao.find(BSONDocument()).collect[List]()
FutureProducts.map { prod => Ok(JsArray(prod.map {
        a => Json.obj("name" -> JsObject(a.name.get), "image" -> JsObject(a.image))
            }))
}}

Upvotes: 1

Related Questions