您可以使用基本的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"}]}'
Run Code Online (Sandbox Code Playgroud)
但是,你真的需要考虑某些事情......
<node>text<another>woo</another>text</node>样式标记?如果是这样,你将如何处理?它不是两者之间平滑的1:1映射......但是对于给定的特定格式的XML,可能会提出给定的特定格式的Json.
要从文档中获取名称(请参阅注释),您可以执行以下操作:
def jsonObject = [ (parsed.name()): parsed.collect {
[ (it.name()): it.text() ]
} ]
Run Code Online (Sandbox Code Playgroud)
您可以添加更深入的支持:
// 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"]}]}]}'
Run Code Online (Sandbox Code Playgroud)
再次,所有先前的警告仍然适用(但此时应该听到更大声);-)
这可以做到这一点:http://www.json.org/java/
在撰写本答案时,可以在以下网址找到该jar:http://mvnrepository.com/artifact/org.json/json/20140107
以下显示了用法.
进口:
import org.json.JSONObject
import org.json.XML
Run Code Online (Sandbox Code Playgroud)
转换:
static String convert(final String input) {
int textIndent = 2
JSONObject xmlJSONObj = XML.toJSONObject(input)
xmlJSONObj.toString(textIndent)
}
Run Code Online (Sandbox Code Playgroud)
相关的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)
}
Run Code Online (Sandbox Code Playgroud)
希望这有助于任何仍需要解决此问题的人.
我有点迟到了,但以下代码会将任何 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()
Run Code Online (Sandbox Code Playgroud)
转换 XML...
<root>
<node>Tim</node>
<node>Tom</node>
</root>
Run Code Online (Sandbox Code Playgroud)
进入...
{
"name": "root",
"children": [
{
"name": "node",
"value": "Tim"
},
{
"name": "node",
"value": "Tom"
}
]
}
Run Code Online (Sandbox Code Playgroud)
欢迎反馈/改进!
| 归档时间: |
|
| 查看次数: |
16979 次 |
| 最近记录: |