【发布时间】:2015-02-24 06:11:40
【问题描述】:
所有,我必须调用第三方服务,它会以 XML 格式返回响应,因为我无法访问 XML。有什么方法可以将 XML 响应转换为 json 以便我可以在我的项目中使用
我已经尝试过了,但我不想硬编码我的回复
// Given an XML string
def xml = '''<root>
| <node>Tim</node>
| <node>Tom</node>
| <node>
| <anotherNode>another</anotherNode>
| </node>
|</root>'''.stripMargin()
// Parse it
def parsed = new XmlParser().parseText( xml )
// Deal with each node:
def handle
handle = { node ->
if( node instanceof String ) {
node
}
else {
[ (node.name()): node.collect( handle ) ]
}
}
// Convert it to a Map containing a List of Maps
def jsonObject = [ (parsed.name()): parsed.collect { node ->
[ (node.name()): node.collect( handle ) ]
} ]
// And dump it as Json
def json = new groovy.json.JsonBuilder( jsonObject )
// Check it's what we expected
assert json.toString() == '{"root":[{"node":["Tim"]},{"node":["Tom"]},{"node":[{"anotherNode":["another"]}]}]}'
帮助表示赞赏。
【问题讨论】:
标签: javascript ajax xml json cross-domain