Thursday, February 28, 2013

Converting Play 2.1 JSON to Scala XML

Working with JSON and XML is pretty simple in Play-framework. For JSON, it is recommended to use Play's type-class based library.

I recently, came across a scenario where I had to convert Play 2.1 JSON to Scala XML and vice versa. I didn't find any internal classes in Play which could handle this. Lift provides a tool to handle a similar conversion.

To convert the JSON into XML I used recursion. Although, the scala.xml.Elem constructor allows only one Node to be added as child, there is another method copy, which takes in a Seq[Node] as child.  

To handle conversion from XML to JSON, I modified the toJson method in Lift to result in Play JSON. 

Link to gist



1 comment:

  1. This is wonderful code. Thank you very much for sharing this.

    ReplyDelete

Note: Only a member of this blog may post a comment.