Converting json instance type and list in Playframework

I found the easiest way to convert your instance to/from json in Playframework is to use the following code:

For type instance

I'm just making use of Json.writes and Json.reads to do the dirty work.

case class CartProduct(id : String, qty : Double)

object CartProduct {

  implicit val cartProductWrites  = Json.writes[CartProduct] // convert to json 
  implicit val cartProductReads  = Json.reads[CartProduct]  // example - get from post 

The code below works too, but a bit too long for me.

implicit val cartProductReads: Reads[CartProduct] = (
  (JsPath \ "id").read[String] and
    (JsPath \ "qty").read[Double]
  )(CartProduct.apply _)

Somewhere in your controller, you might have the following code to write your instance in json format.

def getProduct(productId : String) = Action {
  val p = new Product("Demo", "Demo App", 12.0)

To get back your instance from a HTTP post

def add = Action(BodyParsers.parse.json)
  request => val product = request.body.validate[Product]

And finally your client side post could look something like this.

  type: "POST",
  url: 'http://localhost:9000/cart/add',
  data: JSON.stringify({ 'id' : 'testg', 'qty': 12}),
  dataType: 'json',
  contentType : 'application/json'

For arrays

If you looking at return your product list as array, you can use Json.arr in getAll method in your controller :-

class Catalog extends Controller {

  def getAll() = Action {
    val result = getFakeProduct()

  def getFakeProduct(): List[Product] = {
    var a = new Product("test1", "test desc", 12.0)
    var b = new Product("test1", "test desc", 12.0)
    return  a :: b :: Nil  }


Popular posts from this blog

OpenCover code coverage for .Net Core

ionic2 cordova build android - Unable resolve gradle 2.2.3

Using Custom DLL with IronPython / Scripts