Reputation: 111
I want to convert below XML object,
val xml = <body>
<para>first</para>
<para>second</para>
<sometag>xyz</sometag>
</body>
to JSON
{"body":{"para":["first","second"],"sometag":"xyz"}}
I've tried below scala libraries,
1. net.liftweb | lift-json_2.11 | 3.3.0
import net.liftweb._
import net.liftweb.json.Xml.XmlNode
import net.liftweb.json.Xml
import net.liftweb.json._
println("JSON STRING" + compactRender(toJson(xml)))
output: {"body":{"para":"first","para":"second","sometag":"xyz"}}
2. org.json4s | json4s-xml_2.11 | 3.6.5
import org.json4s.Xml.{ toJson, toXml }
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods.{ render, pretty, compact }
println("JSON String:" + compact(render(toJSON(xml))))
output: {"body":{"para":"first","para":"second","sometag":"xyz"}}
in both the cases, I see duplicate keys (note that para is seen twice) which is invalid in JSON. Rather, my expectation is, if a duplicate XML tag is seen in XML document, the convertor must places those values in array as shown below
{"body":{"para":["first","second"],"sometag":"xyz"}}
Upvotes: 1
Views: 1006
Reputation: 345
(it's a little late.) you can use org.json Java library for this.
import org.json.XML
val xml = """<body>
<para>first</para>
<para>second</para>
<sometag>xyz</sometag>
</body>"""
val jsonStr = XML.toJSONObject(xmlData).toString( indentFactor=4 )
println(jsonStr)
Output:
{"body": {
"para": [
"first",
"second"
],
"sometag": "xyz"
}}
Note: The order of the JSON elements may vary.
Upvotes: 1