【问题标题】:Groovy: Nested XML to JsonGroovy:将 XML 嵌套到 Json
【发布时间】:2019-03-08 12:30:32
【问题描述】:

我是 groovy 的新手。我的要求有问题。

我的要求是将嵌套的 XML 转换为 Json

下面是输入文件:

<root>
    <Account>
        <name>name</name>
        <age>age</age>
    </Account>
    <Assets>
        <record>
            <info>info</info>
            <details>details</details>
            <attributes>
                <property>property</property>
            </attributes>
        </record>
        <record>
            <info>info 1</info>
            <details>details 1</details>
            <attributes>
                <property>property 1</property>
            </attributes>
        </record>
    </Assets>
</root>

首选输出如下:

{
 "root":[
 {"account":
 "records":{
 {"name":"name","age":"age"}
}
},
{"assets":
"records":{
"info":"info","details":"details"
},
{"attributes":{"property":"property"}}
,
{
"info":"info 1","details 1":"details 1"
},
{"attributes":{"property":"property 1"}}
}
]
}    

Assets 段中,我们将获得n 的记录数,所有记录数据都应填充在"record":{} 中。

有什么办法可以做到吗?

您的任何意见都将受到高度赞赏

【问题讨论】:

  • 为什么"records":[ {"account": "records":[ {"name":"name","age":"age"} ] 中的records 都是一个列表?
  • 嗨,蒂姆,是的,这是预料之中的。但是现在要求发生了变化,我已经更新了我的问题并输出了有效负载

标签: json xml groovy


【解决方案1】:

更新代码:

import groovy.json.JsonBuilder
def text = '''
<root>
    <Account>
        <name>name</name>
        <age>age</age>
    </Account>
    <Assets>
        <record>
            <info>info</info>
            <details>details</details>
            <attributes>
                <property>property</property>
            </attributes>
        </record>
        <record>
            <info>info 1</info>
            <details>details 1</details>
            <attributes>
                <property>property 1</property>
            </attributes>
        </record>
    </Assets>
</root>
'''

def toJsonBuilder(xml){
    new groovy.json.JsonBuilder(build(new XmlParser().parseText(xml)))
}
def build(node){
    if (node instanceof String)
        return 
    def map = [ "${node.name()}" : '' ]
    if (!node.children().isEmpty() && !(node.children().get(0) instanceof String)) { 
        map.put("${node.name()}", node.children().collect{build(it)}.findAll{it != null})
    } else if (node.text() != ''){
        map.put("${node.name()}", node.text())
    }
    map
}
println toJsonBuilder(text).toPrettyString()

【讨论】:

  • 嗨,Bhanu,我已经尝试过您的代码,但我无法在 [] 输出中封装记录详细信息,如下所示 { "Account": { "name": "name", "年龄”:“年龄”},“资产”:{“记录”:{“信息”:“信息 1”,“详细信息”:“详细信息 1”,“属性”:{“属性”:“属性 1”} } } } 代码在转换为 json 时也排除了第二条记录。你能帮帮我吗?
  • 嗨,Bhanu,第二条记录不包括在内的原因是因为第一条和第二条都具有相同的名称,我尝试使用两个不同的名称。那么有没有办法打印同名记录的数据呢?
  • @vineethB。抱歉,是我的错。现在我更新了我的代码。看看这个。
  • 嗨 Bhanuchander,我的要求发生了一些变化。而不是在 [ ] 中生成迭代记录,现在他们想要在 { } 中并且您的代码输出是这样的。它将所有单独的记录创建为单个 json 结构 "Account": [ { "name": "vineeth" }, { "age": "21" } ]
猜你喜欢
  • 2022-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 2019-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多