If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Friday, October 5, 2012

Using Play JSON library to expose JSON services

Currently I am experimenting with Playframework. Today we will see how easy it is to generate a JSON response. Let us first take a look at our domain model
package models

case class Contact(firstName: String, lastName: String, age: Int)

object Contact {
  val contacts = Set(
      Contact("Robby", "Pelssers", 35),
      Contact("Davy", "Pelssers", 35),
      Contact("Lindsey", "Pelssers", 9)
  )
  
  def findAll = this.contacts.toList.sortBy(_.firstName)

}
Next let us take a look at a simple controller returning contacts in JSON format
package controllers

import play.api.mvc.{ Action, Controller }
import play.api.libs.json.Json._
import models.Contact

object Contacts extends Controller {

  def toJSON = Action { implicit request =>
    val contacts = Contact.findAll   
    val json = 
      toJson(
        contacts.map(
            contact => toJson(
                Map("firstName" -> toJson(contact.firstName), 
                    "lastName" -> toJson(contact.lastName), 
                    "age" -> toJson(contact.age))
            )    
        )
      )
     
    Ok(json)
  }
  
}

Now it's a matter of mapping a URL to our controller method.
GET     /contacts.json              controllers.Contacts.toJSON
Now let's see if our response looks ok by using curl
$ curl --request GET --include http://localhost:9000/contacts.json
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 160

[{"firstName":"Davy","lastName":"Pelssers","age":35},{"firstName":"Lindsey","lastName":"Pelssers","age":9},{"firstName":"Robby","lastName":"Pelssers","age":35}]

No comments:

Post a Comment