Skip to content
Snippets Groups Projects
Commit 7daa252b authored by Will Billingsley's avatar Will Billingsley
Browse files

Added Play JSON libraries and examples

parent c75f277f
No related branches found
No related tags found
No related merge requests found
package controllers
import javax.inject._
import scala.util.Random
import play.api.libs.json.{JsValue, Json}
import play.api.mvc._
@Singleton
class ExamplesController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
/**
* A controller action that receives JSON as input.
* The bodyParser parses the content for you, and leaves the parsed JSON in req.body
*
* @return
*/
def receiveJsonPost():Action[JsValue] = Action(bodyParser = parse.json) { req =>
val json:JsValue = req.body
/*
* If the JSON is { name: "Fred" }
* then this gets the value that's in name
*/
val name = (json \ "name").as[String]
Ok(s"Hello $name")
}
/**
* A controller that outputs some JSON
* @return
*/
def returnJson():Action[AnyContent] = Action { req =>
Ok(Json.obj(
"Hello" -> Seq("World", "Bob", "Alice"),
"Goodbye" -> Json.obj(
"Mr" -> "Chips"
)
))
}
/**
* A controller that takes an optional id in the query string.
* If we get an ID, we return it. If not, we're just allocating a random ID and then
* redirecting so we have an ID.
* @param id
* @return
*/
def game(id:Option[String]) = Action { req =>
def randomId = Random.alphanumeric.take(8).toString
id match {
case Some(s) => Ok(s"It was $s")
case None => Redirect("/examples/call", Map("id" -> Seq(randomId)))
}
}
}
......@@ -12,6 +12,9 @@ resolvers += "Hopper releases" at "http://hopper.une.edu.au/artifactory/libs-rel
resolvers += "Hopper snapshots" at "http://hopper.une.edu.au/artifactory/libs-snapshot"
libraryDependencies += guice
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.6.10"
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "3.1.2" % Test
// Adds additional packages into Twirl
......
......@@ -6,5 +6,10 @@
# An example controller showing a sample home page
GET / controllers.HomeController.index
GET /example/json controllers.ExamplesController.returnJson()
POST /example/json controllers.ExamplesController.receiveJsonPost()
GET /example/game controllers.ExamplesController.game(id:Option[String])
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment