在Groovy中将XML转换为JSON [英] Converting XML to JSON in Groovy

查看:191
本文介绍了在Groovy中将XML转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用groovy将xml转换为JSON。我了解转换的具体情况取决于我的偏好,但是有人可以推荐我应该使用哪些库和方法,并向我提供一些有关为什么/如何使用它们的信息?我正在使用groovy,因为我被告知这是一个非常有效的解析器,所以我正在寻找可以利用这个优势的库。

谢谢!

解决方案

您可以使用基本的Groovy完成所有工作:

  //给定一个XML字符串
def xml ='''< root>
| <节点>添< /节点>
| <节点>汤姆与LT; /节点>
|< / root>'''。stripMargin()

//解析它
def parsed = new XmlParser()。parseText(xml)

//将其转换为包含地图列表的地图
def jsonObject = [root:parsed.node.collect {
[node:it.text()]
}]

//并将其转储为Json
def json = new groovy.json.JsonBuilder(jsonObject)

//检查它是我们所期望的
assert json.toString()=='{root:[{node:Tim},{node:Tom}]}'

然而,你真的需要考虑某些事情......




  • 如何表示属性?

  • 您的XML是否包含< node>文本< another> woo< / another> text< / node> 样式标记?如果是这样,你将如何处理?

  • CDATA?注释?


    这两者之间不是平滑的1:1映射......但对于给定的特定格式的XML,它可能有可能想出一个特定的Json格式。

    更新:



    你可以这样做:

      def jsonObject = [(parsed.name()):parsed.collect {
    [(it.name()):it.text()]
    }]



    更新2



    您可以添加对更大深度的支持:

      //给定一个XML字符串
    def xml ='''< root>
    | <节点>添< /节点>
    | <节点>汤姆与LT; /节点>
    | <节点>
    | < anotherNode>另一个< / anotherNode>
    | < /节点>
    |< / root>'''。stripMargin()

    //解析它
    def parsed = new XmlParser()。parseText(xml)

    //处理每个节点:$ b​​ $ b def handle
    handle = {node - >
    if(node instanceof String){
    node
    }
    else {
    [(node.name()):node.collect(handle)]
    }
    }
    //将其转换为包含地图列表的地图
    def jsonObject = [(parsed.name()):parsed.collect {node - >
    [(node.name()):node.collect(handle)]
    }]

    //将其转储为Json
    def json = new groovy .json.JsonBuilder(jsonObject)

    //检查它是我们期望的
    断言json.toString()=='{root:[{node:[Tim ]},{node:[Tom]},{node:[{anotherNode:[another]}]}]}'
    pre>

    同样,以前的所有警告仍然是正确的(但在这一点上应该听起来有点大声); - )


    I wish to convert xml to JSON using groovy. I understand the specifics of conversion is dependent on my preferences, but could someone please recommend which libraries and methods I should be using and provide me with a little information on why/how to use them? I am using groovy as I have been told it is a very effective parser, so I am looking for libraries that will take advantage of this

    Thanks!

    解决方案

    You can do it all with basic 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"}]}'
    

    HOWEVER, you really need to think about certain things...

    • How are you going to represent Attributes?
    • Will your XML contain <node>text<another>woo</another>text</node> style markup? If so, how are you going to handle that?
    • CDATA? Comments? etc?

    It's not a smooth 1:1 mapping between the two... But for a given specific format of XML, it may be possible to come up with a given specific format of Json.

    Update:

    To get the names from the document (see comment), you can do:

    def jsonObject = [ (parsed.name()): parsed.collect {
      [ (it.name()): it.text() ]
    } ]
    

    Update 2

    You can add support for greater depth with:

    // 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"]}]}]}'
    

    Again, all the previous warnings still hold true (but should be heard a little louder at this point) ;-)

    这篇关于在Groovy中将XML转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆