I wish to convert xml to JSON using groovy. I understand the specifics of conversion is dependent on my preferences, but could someone please recommend which libraries and methods I should be using and provide me with a little information on why/how to use them? I am using groovy as I have been told it is a very effective parser, so I am looking for libraries that will take advantage of this
Thanks!
I'm a bit late to the party, but the following code will convert any XML into a consistent JSON format:
def toJsonBuilder(xml){
def pojo = build(new XmlParser().parseText(xml))
new groovy.json.JsonBuilder(pojo)
}
def build(node){
if (node instanceof String){
return // ignore strings...
}
def map = ['name': node.name()]
if (!node.attributes().isEmpty()) {
map.put('attributes', node.attributes().collectEntries{it})
}
if (!node.children().isEmpty() && !(node.children().get(0) instanceof String)) {
map.put('children', node.children().collect{build(it)}.findAll{it != null})
} else if (node.text() != ''){
map.put('value', node.text())
}
map
}
toJsonBuilder(xml1).toPrettyString()
Converts the XML...
<root>
<node>Tim</node>
<node>Tom</node>
</root>
Into...
{
"name": "root",
"children": [
{
"name": "node",
"value": "Tim"
},
{
"name": "node",
"value": "Tom"
}
]
}
Feedback/improvements welcome!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With