5
votes

I'm new to both Play! & Scala, but I'm trying to make a service that will map the JSON request to a Map[String,JsObject] (or Map[String,JsValue], I'm not sure about the distinction), and then output a list of the keys recursively through the map (preferably as a tree).

But I'm having start issues:

def genericJSONResponse = Action(parse.json) {
  request => request.body
  var keys = request.keys
  Ok("OK")
}

What I would expect here was for keys to be filled with the keys from the request, but of course, it doesn't compile. How should I approach this, given the description above?

Thanks in advance for helping out a Scala noob :-)

Nik

1
Have you read through this wiki? github.com/playframework/Play20/wiki/ScalaJsonRequests You'll have to map the keys manually or using an implicit object to map them to an object. github.com/playframework/Play20/wiki/ScalaJsonGenericsDrew H
Also something to bear in mind is using mutable values/collections in scala is not advised - as can be seen herejesus g_force Harris

1 Answers

16
votes

JsValue is the base class for all JSON values. JsObject is a subtype of JsValue (along with JsNull, JsUndefined, JsBoolean, JsNumber, JsString, and JsArray). Take a look at JSON spec if it's unclear: http://json.org/

If you know that the JSON in the body request is a JSON object (as opposed to other types listed above) you can pattern-match it:

def genericJSONResponse = Action(parse.json) { request =>
  request.body match {
    case JsObject(fields) => Ok("received object:" + fields.toMap + '\n')
    case _ => Ok("received something else: " + request.body + '\n')
  }
}

fields.toMap is of type you wanted: Map[(String, JsValue)] so you can use map or collect to process the object's keys recursively. (By the way, you can use fields directly, since it's a Seq[(String, JsValue)] and supports map and collect as well).