Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Groovy中将XML转换为JSON_Xml_Json_Groovy_Converter - Fatal编程技术网

在Groovy中将XML转换为JSON

在Groovy中将XML转换为JSON,xml,json,groovy,converter,Xml,Json,Groovy,Converter,我希望使用groovy将xml转换为JSON。我知道转换的具体细节取决于我的偏好,但有人能推荐我应该使用哪些库和方法,并提供一些关于为什么/如何使用它们的信息吗?我正在使用groovy,因为有人告诉我它是一个非常有效的解析器,所以我正在寻找能够利用它的库 谢谢 您可以使用基本Groovy完成这一切: // Given an XML string def xml = '''<root> | <node>Tim</node>

我希望使用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"}]}'
更新2 您可以通过以下方式添加对更大深度的支持:

// 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"]}]}]}'
//给定一个XML字符串
def xml=''
|提姆
|汤姆
|    
|另一个
|    
|''.stripMargin()
//解析它
def parsed=new XmlParser().parseText(xml)
//处理每个节点:
def手柄
句柄={node->
if(字符串的节点实例){
节点
}
否则{
[(node.name()):node.collect(句柄)]
}
}
//将其转换为包含地图列表的地图
def jsonObject=[(parsed.name()):parsed.collect{node->
[(node.name()):node.collect(句柄)]
} ]
//并将其作为Json转储
def json=new groovy.json.JsonBuilder(jsonObject)
//检查它是否符合我们的预期
assert json.toString()='{“root”:[{“node”:[{“Tim”]},{“node”:[“Tom”]},{“node”:[{“另一个”]}]}'

同样,所有之前的警告仍然有效(但此时应该听到更大的声音);-)

我使用staxon将复杂的XML转换成JSON。这包括具有属性的元素

下面是一个将xml转换为json的示例


我来晚了一点,但是下面的代码将把任何XML转换成一致的JSON格式:

def-toJsonBuilder(xml){
def pojo=build(新的XmlParser().parseText(xml))
新的groovy.json.JsonBuilder(pojo)
}
def生成(节点){
如果(字符串的节点实例){
返回//忽略字符串。。。
}
def map=['name':node.name()]
如果(!node.attributes().isEmpty()){
map.put('attributes',node.attributes().collectEntries{it})
}
如果(!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())
}
地图
}
toJsonBuilder(xml1.toPrettyString())
转换XML


提姆
汤姆
进入

{
“名称”:“根”,
“儿童”:[
{
“名称”:“节点”,
“值”:“Tim”
},
{
“名称”:“节点”,
“价值”:“汤姆”
}
]
}
欢迎反馈/改进

这将完成工作:

在撰写此答案时,jar可在以下网站上获得:

下面显示了用法


进口:

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)
}
void“如果标签和内容可用,则将内容放入内容属性”(){
鉴于:
字符串xml1=''
你好
'''
以及:
字符串xml2=''
'''
以及:
字符串xml3=''
'''
以及:
字符串json=''
{“标记”:{
“内容”:“你好”,
“属性1”:“值”
}}
'''
期望:
StringUtils.deleteWhitespace(转换(xml1))==StringUtils.deleteWhitespace(json)
StringUtils.deleteWhitespace(转换(xml2))==StringUtils.deleteWhitespace(json)
StringUtils.deleteWhitespace(转换(xml3))==StringUtils.deleteWhitespace(json)
}
void“内容属性将作为数组与内容合并”(){
鉴于:
字符串xml=“”
你好
'''
以及:
字符串json=''
{“标记”:{
“内容”:[
“与放入内容相同”,
“你好”
],
“属性1”:“值”
}}
'''
期望:
StringUtils.deleteWhitespace(转换(xml))==StringUtils.deleteWhitespace(json)
}
void“如果没有其他属性,则内容属性将被忽略,并在数组中创建数组。”(){
鉴于:
字符串xml=“”
你好
'''
以及:
字符串notExpected=“”
{“标记”:{[
“与放入内容相同”,
“你好”
]}
}
'''
字符串json=''
{“标记”:[[
“与放入内容相同”,
“你好”
]]
}
'''
期望:
StringUtils.deleteWhitespace(转换(xml))!=StringUtils.deleteWhitespace(notExpected)
StringUtils.deleteWhitespace(转换(xml))==StringUtils.deleteWhitespace(json)
}

希望这能帮助仍需要解决此问题的任何人。

非常感谢您的帮助!然而,关于你的解决方案,我还有一个问题。。定义jsonObject时,您指定了“root:”和“node:”,groovy有没有一种方法可以通过分析xml属性的名称来自动指定这些名称,而无需假设?@TomHadkiss更新了答案,展示了如何做到这一点(但是,对于更复杂的xml文档,情况会变得更糟);-)抱歉,谷歌没有给我任何答案。。您建议如何使用更深入的XML?例如another@TomHadkiss更新了,但是你应该再次听到一个警报,因为我们正在接近这条路的尽头,使用这种通用转换超级简单,只需几行代码。它还处理XML属性。
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)
}