ps0604 ps0604 - 8 days ago 6
Scala Question

Returning future list in Play for Scala json

Apologies if this is a simple question. I need to return the Json structure in the

Action.async
method, however I'm not sure how to create a future that embeds a list that's already a future. Any suggestions?

case class Clazz (a: Int, b: Int)

def index = Action.async {
val json = JsObject(Seq(
"x" -> JsString("1"),
"list" -> Json.toJson(getList) // this line does not compile
))
Ok(json)
}


def getList = Future {
val c1 = Clazz (1,1)
val c2 = Clazz (2,2)
val list = List(c1,c2)
list
}


UPDATE:

Added the following Writes object:

implicit val cc: Writes[Clazz] = (
(JsPath \ "a").write[Int] and
(JsPath \ "b").write[Int]
) (unlift(Clazz.unapply))

Answer

You have to use the map function to get a new Future with the expected content:

def index = Action.async { 
  val eventualList: Future[List[Clazz]] = getList
  eventualList.map { list: List[Clazz] =>
    val json = JsObject(Seq(
      "x" -> JsString("1"),
      "list" -> Json.toJson(list) 
    ))
    Ok(json)
  }
}
Comments