简体   繁体   中英

Groovy: Json to XML dynamic

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM