如何在Groovy中将xml转换为json?
How to convert xml to json in Groovy?
在groovy中我有下面的xml
<data>
<row>
<id>USA</id>
<value>United States of America</value>
</row>
<row>
<id>CAN</id>
<value>Canada</value>
</row>
</data>
我需要将groovy中的上面的xml转换成下面的json格式
{
"data": [
{
"KEY": "USA",
"VALUE": "United States of America"
},
{
"KEY": "CAN",
"VALUE": "Canada"
}
]
}
如有任何帮助,我们将不胜感激。
谢谢
哈里
给你:
//Pass xml as string to below parseText method
def parsed = new XmlSlurper().parseText(xml)
//Create the map as needed out of parsed xml
def map = [(parsed[0].name): parsed.'**'
.findAll{it.name() == 'row'}
.collect{ row ->
row.collectEntries{[KEY: row.id.text(), VALUE:row.value.text()]}
}
]
println new groovy.json.JsonBuilder(map).toPrettyString()
您可以快速在线试用Demo
在groovy中我有下面的xml
<data>
<row>
<id>USA</id>
<value>United States of America</value>
</row>
<row>
<id>CAN</id>
<value>Canada</value>
</row>
</data>
我需要将groovy中的上面的xml转换成下面的json格式
{
"data": [
{
"KEY": "USA",
"VALUE": "United States of America"
},
{
"KEY": "CAN",
"VALUE": "Canada"
}
]
}
如有任何帮助,我们将不胜感激。
谢谢
哈里
给你:
//Pass xml as string to below parseText method
def parsed = new XmlSlurper().parseText(xml)
//Create the map as needed out of parsed xml
def map = [(parsed[0].name): parsed.'**'
.findAll{it.name() == 'row'}
.collect{ row ->
row.collectEntries{[KEY: row.id.text(), VALUE:row.value.text()]}
}
]
println new groovy.json.JsonBuilder(map).toPrettyString()
您可以快速在线试用Demo