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  }


Perry James said…

Hi everybody, I hope you are doing good. Dear admin I had scroll down your site and found it really useful for web development tools. Since I am a developer, I most often refer people to use best website in the town for web development. Your efforts are really appreciable. We also provide web development tool. Here is the link of our site jsononline

Popular posts from this blog

Solving Sonarqube :- Project was never analyzed. A regular analysis is required before a branch analysis

spark - pyspark reading from excel files