Simple JSON for XML and then XML for JSON using Scala

I am looking for a native Scala solution to change this:

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

in it:

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

and back (XML back to JSON).

I understand that there are Java libraries that I can use to help me, but this should be a simple problem, and in order to better understand Scala and functional programming, I would be very pleased to see how to do this with regular Scala.

Similar questions were asked for many other languages ​​in StackOverflow, so having equal in Scala will make the link more complete.

+1
source share
1 answer

I think the simplest solution would be something like that:

 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 general way with case classes to support a stronger matching syntax for the xml2json variant

+2
source

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


All Articles