Groovy:Json转为XML动态 [英] Groovy: Json to XML dynamic

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

问题描述

  {
test:{
a :A,
b:B
}
}

要生成的最终XML结果是,测试json对象中存在的元素应该转换为XML,并添加另一个XML标记以证明元素存在为true。
如下:

 < test> 
< message>
< a> A< / a>
< b> B< / b>
< / message>
< booleanMessage>
< a> true< / a>
< b> true< / b>
< / booleanMessage>
< / test>

我们如何使用groovy转换来做到这一点?



任何帮助表示赞赏。



谢谢!

解决方案

您可以结合使用 JsonSlurper MarkupBuilder 来实现这一目标。

  def json = new groovy.json.JsonSlurper()。parseText('''
{
test: {
a:A,
b:B
}
}
''')

def sw = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(sw)

json.each {prop - >
xml。$ prop.key{
message {
prop.value.each {nestedProp - >
$ nestedProp.key(nestedProp.value)
}
}
booleanMessage {
prop.value.each {p - >
$ p.key('true')
}
}
}
}
println sw.toString()


We have a json like following

{
  "test" : { 
    "a" : "A", 
    "b" : "B"
  }
}

The final XML outcome to be generated is if there is an element present in test json object that should be converted into XML and another XML tag to be added to demonstrate that the element present is true. like following:

<test>
  <message>
    <a>A</a>
    <b>B</b>
  </message>
  <booleanMessage>
    <a>true</a>
    <b>true</b>
  </booleanMessage>
</test>

How can we use groovy transformation to do so?

Any help is appreciated.

Thanks!

解决方案

You can use a combination of JsonSlurper and MarkupBuilder to achieve this.

def json = new groovy.json.JsonSlurper().parseText('''
    {
      "test" : { 
        "a" : "A", 
        "b" : "B"
       }
    }
''')

def sw = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(sw)

json.each { prop ->
    xml."$prop.key" {
        message {
            prop.value.each { nestedProp ->            
                "$nestedProp.key"(nestedProp.value)
            }   
        }
        booleanMessage {
            prop.value.each  { p ->
                "$p.key"('true')
            }               
        }
    }
}
println sw.toString()

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

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