[英]Converting XML to JSON in Groovy
我希望使用groovy将xml转换为JSON。 我了解转换的具体细节取决于我的偏好,但是有人可以建议我应该使用哪些库和方法,并向我提供一些有关为什么/如何使用它们的信息。 有人告诉我这是一个非常有效的解析器,因此我正在使用groovy,因此我正在寻找可以利用此功能的库
谢谢!
您可以使用基本的Groovy完成所有操作:
// Given an XML string
def xml = '''<root>
| <node>Tim</node>
| <node>Tom</node>
|</root>'''.stripMargin()
// Parse it
def parsed = new XmlParser().parseText( xml )
// Convert it to a Map containing a List of Maps
def jsonObject = [ root: parsed.node.collect {
[ node: it.text() ]
} ]
// 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>text<another>woo</another>text</node>
样式标记? 如果是这样,您将如何处理? 两者之间不是平滑的1:1映射...但是对于给定的XML特定格式,可能可以提出给定的Json特定格式。
要从文档中获取名称(请参阅评论),您可以执行以下操作:
def jsonObject = [ (parsed.name()): parsed.collect {
[ (it.name()): it.text() ]
} ]
您可以通过以下方式增加对更深层次的支持:
// 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"]}]}]}'
同样,所有先前的警告仍然成立(但在这一点上应该听到一些大声);-)
这样就可以了: http : //www.json.org/java/
在编写此答案时,可以在以下位置找到该jar: http : //mvnrepository.com/artifact/org.json/json/20140107
下面显示了用法。
进口:
import org.json.JSONObject
import org.json.XML
转换:
static String convert(final String input) {
int textIndent = 2
JSONObject xmlJSONObj = XML.toJSONObject(input)
xmlJSONObj.toString(textIndent)
}
相关的Spock测试以显示我们需要注意的某些情况:
void "If tag and content are available, the content is put into a content attribute"() {
given:
String xml1 = '''
<tag attr1="value">
hello
</tag>
'''
and:
String xml2 = '''
<tag attr1="value" content="hello"></tag>
'''
and:
String xml3 = '''
<tag attr1="value" content="hello" />
'''
and:
String json = '''
{"tag": {
"content": "hello",
"attr1": "value"
}}
'''
expect:
StringUtils.deleteWhitespace(convert(xml1)) == StringUtils.deleteWhitespace(json)
StringUtils.deleteWhitespace(convert(xml2)) == StringUtils.deleteWhitespace(json)
StringUtils.deleteWhitespace(convert(xml3)) == StringUtils.deleteWhitespace(json)
}
void "The content attribute would be merged with the content as an array"() {
given:
String xml = '''
<tag content="same as putting into the content"
attr1="value">
hello
</tag>
'''
and:
String json = '''
{"tag": {
"content": [
"same as putting into the content",
"hello"
],
"attr1": "value"
}}
'''
expect:
StringUtils.deleteWhitespace(convert(xml)) == StringUtils.deleteWhitespace(json)
}
void "If no additional attributes, the content attribute would be omitted, and it creates array in array instead"() {
given:
String xml = '''
<tag content="same as putting into the content" >
hello
</tag>
'''
and:
String notExpected = '''
{"tag": {[
"same as putting into the content",
"hello"
]}
}
'''
String json = '''
{"tag": [[
"same as putting into the content",
"hello"
]]
}
'''
expect:
StringUtils.deleteWhitespace(convert(xml)) != StringUtils.deleteWhitespace(notExpected)
StringUtils.deleteWhitespace(convert(xml)) == StringUtils.deleteWhitespace(json)
}
希望这对仍然需要解决此问题的人有所帮助。
我参加聚会有点晚,但是下面的代码会将所有XML转换为一致的JSON格式:
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()
转换XML ...
<root>
<node>Tim</node>
<node>Tom</node>
</root>
进...
{
"name": "root",
"children": [
{
"name": "node",
"value": "Tim"
},
{
"name": "node",
"value": "Tom"
}
]
}
欢迎反馈/改进!
我利用staxon使用staxon将复杂的XML转换为JSON。 这包括具有属性的元素。
以下是将xml转换为json的示例。
https://github.com/beckchr/staxon/wiki/Converting-XML-to-JSON
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.