Forum Discussion

tomaszarmata's avatar
tomaszarmata
Contributor
10 years ago

Bulding json from xml

Hello,

 

I have tried to build json body from xml. Take file, parse it, make groovy object, then json.

 

I build groovyObject first becouse I need in next steps to set up values for method, path and synchronize-type. I need also to be aware of xml file changes like new parameters etc.

 

I follow up http://stackoverflow.com/questions/18830248/converting-xml-to-json-in-groovy.

 

 

import groovy.json.JsonBuilder

def doc = '''
<resources>
	<resource>
		<name>synchronize</name>
		<parameters>
			<parameter>
				<name>method</name>
			</parameter>
			<parameter>
				<name>path</name>
			</parameter>
			<parameter>
				<name>synchronization-type</name>
			</parameter>
		</parameters>
	</resource>
</resources>
'''

def parsedXml = new XmlParser().parseText( doc )

def groovyObject = [
	(parsedXml.resource.name.text()): parsedXml.resource.parameters.parameter.collect {
		[
			(it.text()): null
		]
	}
]

def jsonObject = new JsonBuilder ( groovyObject )
log.info jsonObject

 

But it return

 

{
    "synchronize": [
        {
            "method": null
        },
        {
            "path": null
        },
        {
            "synchronization-type": null
        }
    ]
}

 

Is there somethink I can do to make script to return:

 

{
    "synchronize": [
        {
            "method": null,
            "path": null,
            "synchronize-type": null
        }
    ]
}

 

 

  • After some discusion i try do it that way.

     

    def rootName = null
    def root = [:]
    def connector = []
    def map = [:]
    
    rootName = parsedXml.resource.name.text()
    parsedXml.resource.parameters.parameter.each{
    	map.put( it.text(), null )
    }
    
    connector.add(map)
    root.put (rootName,connector)
  • After some discusion i try do it that way.

     

    def rootName = null
    def root = [:]
    def connector = []
    def map = [:]
    
    rootName = parsedXml.resource.name.text()
    parsedXml.resource.parameters.parameter.each{
    	map.put( it.text(), null )
    }
    
    connector.add(map)
    root.put (rootName,connector)