Created
May 22, 2013 18:14
-
-
Save tbarker9/5629664 to your computer and use it in GitHub Desktop.
Convert xml to pojo to json using groovy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import groovy.json.JsonBuilder | |
//make sure you have installed groovy | |
//best way to install groovy: http://gvmtool.net/ | |
def carRecords = ''' | |
<records> | |
<car name='HSV Maloo' make='Holden' year='2006'> | |
<country>Australia</country> | |
<record type='speed'>Production Pickup Truck with speed of 271kph</record> | |
</car> | |
<car name='P50' make='Peel' year='1962'> | |
<country>Isle of Man</country> | |
<record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record> | |
</car> | |
<car name='Royale' make='Bugatti' year='1931'> | |
<country>France</country> | |
<record type='price'>Most Valuable Car at $15 million</record> | |
</car> | |
</records> | |
''' | |
def xmlRecords = new XmlSlurper().parseText(carRecords) | |
def jsonObject = [:] | |
jsonObject.records = [] | |
def records = jsonObject.records | |
xmlRecords.car.each {xmlCar -> | |
records.add([car:[name:[email protected](), country: xmlCar.country.text()]]) | |
} | |
def builder = new JsonBuilder(jsonObject) | |
println builder.toPrettyString() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry Peri, wasn't as slick as I hoped