Simple JSON to XML and then XML to JSON using Scal

2019-08-11 17:07发布

问题:

I'm looking for a native Scala solution to change this:

{"name":"jack","greeting":"hello world"}

into this:

<person>
  <name>jack</name>
  <greeting>hello world</name>
</person>

and back again (XML back to JSON).

I realize that there are Java libraries out there that I can use to help me, but this should be a simple problem, and in an effort to better understand Scala and functional programming, I would really love to see how to do this with plain Scala.

Similar questions have been asked for many other languages on StackOverflow, so having an equal in Scala would make the reference more complete.

回答1:

i think, the most simple solution would be something along this lines:

val json = """{"name":"jack","greeting":"hello world"}""";


val jpattern = """\{"name":"(.*)","greeting":"(.*)"\}""".r;

print (json match {
  case jpattern(n,g) => <person><name>{n}</name><greeting>{g}</greeting></person>;
  case _ => ()
})



val xml = <person><name>jack</name><greeting>greeting</greeting></person>

print (xml match {
  case <person><name>{n}</name><greeting>{g}</greeting></person> => """{"name":"%s","greeting":"%s"}""".format(n,g);
  case _ => ()
})

this could probably be done in a more generic way and with case classes to support a nicer match-syntax for the xml2json variant



标签: json scala