Skip to content

Instantly share code, notes, and snippets.

@ymnk
Created October 15, 2008 09:34
Show Gist options
  • Save ymnk/16886 to your computer and use it in GitHub Desktop.
Save ymnk/16886 to your computer and use it in GitHub Desktop.
import scala.xml._
import scala.util.parsing.json.JSON
/**
* The XML2JSON object will transform a string in json format to
* a NodeSeq object.
*/
object JSON2XML {
def apply(input:String):NodeSeq = {
JSON.parse(input) match {
case Some(json) => toXML(json)
case _ => Seq.empty
}
}
private def toXML(json:Any):NodeSeq = json match {
case (k:String, v) if !v.isInstanceOf[List[_]] =>
toElem(k, Text(v.toString))
case (k:String, Nil) => toElem(k, Nil:_*)
case (k:String, v@(_,_)::_) =>
toElem(k, v.flatMap(toXML(_)):_*)
case (k:String, v:List[_]) => // array
for(_v <- v) yield toElem(k, toXML(_v):_* )
case l:List[_] => l.flatMap(toXML(_))
case v => Text(v.toString)
}
private implicit def toSeq(n:Node):NodeSeq=List(n)
private def toElem(label:String, child:Node*) =
Elem(null, label, Null, TopScope, child:_*)
}
object JSON2XMLTest extends Application {
val json="""
{
"Image": {
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": "100"
},
"IDs": [116, 943, 234, 38793]
}
}
"""; // from http://tools.ietf.org/html/rfc4627
// Changing numberParser.
// JSON#perThreadNumberParser has been introduces since 2.7.2.
// JSON.perThreadNumberParser = {_.toInt}
println(new PrettyPrinter(80, 2).formatNodes(JSON2XML(json)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment