Search code examples
xmljsonscalaspray-json

How to convert xml array to json data in scala


I have the xml data in an array as below, i.e, each line corresponds to a single element in array

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
</catalog>

How to convert this xml array to JSON format?


Solution

  • Download lift-json jar from http://scala-tools.org/repo-releases/net/liftweb/

    Be sure to grab the proper library for your Scala version, at time of this post the latest was located at http://scala-tools.org/repo-releases/net/liftweb/lift-json_2.8.1⁄2.3-RC5/

    import net.liftweb.json._
    import net.liftweb.json.JsonAST._
    
    val data = xml.XML.loadFile("quotie.xml")
    val str = Printer.pretty(render(Xml.toJson(data)))
    
    var out_file = new java.io.FileOutputStream("quotie.json")
    var out_stream = new java.io.PrintStream(out_file)
    
    out_stream.print(str)
    out_stream.close