Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve XML and JSON with Play! 2.0

I'm toying around with building a simple application to get my feet wet with Play! 2.0. I would like to be able to serve my resources as XML (ATOM feed, really) and JSON. I know how to do it in 1.2.x, but that way doesn't seem to work with 2.0. Does anyone know how to do it? Examples would be much appreciated.

like image 659
geowa4 Avatar asked Jan 03 '12 23:01

geowa4


1 Answers

For JSON I would recommend you to look at this question How to render JSON response in Play framework v2.0 (latest build from GIT)

XML is far more simpler since you can just call return the result with code like this:

Ok(Xml(xmlString))

But the cleaner way, fot using this functionality is probably to write your own template under views/xml like mdo.scala.xml could be

@(mdo:MyDomainObject)
<?xml version="1.0" encoding="utf-8"?>
<MyDomainObject>
  <name>@mdo.name</name>
  <desc>@mdo.desc</desc>
  <kws>
  @mdo.keywords map { k=>
    <kw>k</kw>
  }
  </kws>
</MyDomainObject>

Then in your Controller

def c = Action {
  val o = MyDomainObject("mine", "for example", List("stack", "over", "flow"))
  Ok(views.xml.mdo(o))
}

Otherwise, you maybe have the similar toXml function to toJson with the help of a marshaling library

like image 152
Andy Petrella Avatar answered Sep 18 '22 13:09

Andy Petrella