How to serve XML and JSON with Play! 2.0

I play with creating a simple application so that my feet are wet from 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 this in 1.2.x, but it doesn't seem to work with 2.0. Does anyone know how to do this? Examples would be greatly appreciated.

+6
source share
1 answer

For JSON, I would recommend that you consider this question. How to display JSON response in Play Framework v2.0 (latest build from GIT)

XML is much simpler because you can simply call the result with the code as follows:

Ok(Xml(xmlString)) 

But a cleaner way using this function is probably to write your own template under views/xml , for example 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 might have a similar toXml toJson function using the marshaling library

+11
source

Source: https://habr.com/ru/post/905026/


All Articles