Groovy: Json to XML dynamic

前端 未结 1 366
温柔的废话
温柔的废话 2021-01-27 10:40

We have a json like following

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

The final XML outcome to be generated is if there i

1条回答
  •  情深已故
    2021-01-27 11:26

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

    0 讨论(0)
提交回复
热议问题