Creating a JSON method in a Play Framework Controller

This is a short example of how to create a Play Framework Controller method that returns JSON. I’ve written this brief tutorial assuming you already know the basics of Play, i.e., what a Controller is, where the routes file, and how to run Play.

As you’ll see, it’s pretty simple. (Or, as a friend says, “It’s obvious ... once you know how to do it.”)

Step 1: Configure the routes file

First, add this code to your conf/routes file:

GET  /json    controllers.Application.json

This states, “When a GET request is called at the /json URI, invoke the json method in the Application object in the controllers package.”

Step 2: Write the json method

Next, create a simple json method in your Application controller, like this:

/**
 * Simple JSON example. Convert a Seq of names to JSON.
 * This code goes in a Play Framework Controller, such as the default
 * 'Application' controller generated by Play.
 */
def json = Action {
  import play.api.libs.json.Json
  val nieces = Seq("Aleka", "Christina", "Emily", "Hannah", "Molly")
  Ok(Json.toJson(nieces))
}

The Seq[String] would normally come from your model object (such as model.User), which would get the data from a data store (relational database or NoSQL), but converting it to JSON would be the same.

Step 3: Access the URI

Now just access the http://localhost:9000/json URL in your browser, and you should see this JSON output in your browser:

["Aleka","Christina","Emily","Hannah","Molly"]

Summary

As you can see, this is about as simple as programming gets. Of course it gets a little more complicated when you need to generate more complicated JSON, but the Play Framework makes that pretty easy also.

For more information on generating JSON in Play, see this URL:

Coming soon

In the very near future I’ll show how to use Async with this approach as well. I’ll also add these recipes to my Play Framework Recipes PDF booklet, along with a JSON reference and examples section.

Sponsor

This tutorial sponsored by:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.